Ruby on rails 在单个资源中嵌套资源
鉴于以下路线:Ruby on rails 在单个资源中嵌套资源,ruby-on-rails,ruby-on-rails-3,rails-routing,Ruby On Rails,Ruby On Rails 3,Rails Routing,鉴于以下路线: resource :public_profile do resources :posts end resource :private_profile do resources :posts end 如何在PostsController中确定嵌套在哪个单一资源中?您可以将它们路由到不同的控制器(通过在路由中指定),这些控制器是从同一“基本”控制器PostsController扩展而来的。在扩展控制器中 识别它们: 例: 控制器呢 class PublicProfileP
resource :public_profile do
resources :posts
end
resource :private_profile do
resources :posts
end
如何在
PostsController
中确定嵌套在哪个单一资源中?您可以将它们路由到不同的控制器(通过在路由中指定),这些控制器是从同一“基本”控制器PostsController扩展而来的。在扩展控制器中
识别它们:
例:
控制器呢
class PublicProfilePostsController < PostsController
before_filter :identify_controller
def identify_controller
@nested_resource_of = :public_profile
end
end
class PrivateProfilePostsController < PostsController
before_filter :identify_controller
def identify_controller
@nested_resource_of = :private_profile
end
end
class PublicProfilePostsController
然后你就可以访问这个变量了
@嵌套的\u资源\u的
在PostsController操作中,可以这样做的一种方法是再创建两个扩展某些主
PostsController的控制器,并使用
resource :public_profile do
resources :posts, controller: "PublicPostsController"
end
resource :private_profile do
resources :posts, controller: "PrivatePostsController"
end
你甚至可以用多种方式来做这件事。比如说,也许拥有
class ProfileController < ApplicationController; end
class PostsController < ApplicationController; end
class Private::ProfileController < ProfileController; end
class Private::PostsController < PostsController; end
class Public::ProfileController < ProfileController; end
class Public::PostsController < PostsController; end
无论您如何设置,您都可以轻松地“知道”嵌套在什么资源中,因为您实际上将在特定于该嵌套的单独控制器中运行,因此可以为特定于该嵌套的逻辑提供一个完美的位置。对于一般逻辑,您需要将其放入父PostsController
另一种方法是在PostsController
之前添加一个过滤器
before_filter :check_nesting
private
def check_nesting
@is_public_profile = params.include?(:public)
end
还有你喜欢的路线
resource :public_profile, public: true do
resources :posts, controller: "PublicPostsController"
end
resource :private_profile, private: true do
resources :posts, controller: "PrivatePostsController"
end
不过我不喜欢这种方法。我最终得到了一个基于您上一个答案的工作版本(在路由中使用参数),但最终完全抛弃了这个概念,采用了更传统的基于资源的方法。
before_filter :check_nesting
private
def check_nesting
@is_public_profile = params.include?(:public)
end
resource :public_profile, public: true do
resources :posts, controller: "PublicPostsController"
end
resource :private_profile, private: true do
resources :posts, controller: "PrivatePostsController"
end