鉴于以下路线:
resource :public_profile do
resources :posts
end
resource :private_profile do
resources :posts
end
在 中,我如何PostsController
确定我嵌套在哪个单一资源中?
鉴于以下路线:
resource :public_profile do
resources :posts
end
resource :private_profile do
resources :posts
end
在 中,我如何PostsController
确定我嵌套在哪个单一资源中?
您可以将它们路由到不同的控制器(通过在路由中指定),这些控制器是从相同的“基本”控制器 PostsController 扩展而来的。在扩展控制器中,您可以识别它们:
前任:
resource :public_profile do
resources :posts, :controller => "public_profile_posts_controller"
end
resource :private_profile do
resources :posts, :controller => "private_profile_posts_controller"
end
和控制器
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
然后您可以访问该变量
@nested_resource_of
在 PostsController 动作中
您可以做到这一点的一种方法是创建另外 2 个扩展一些 main 的控制器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
带路由
resource :public_profile, controller: "Public::ProfileController" do
resources :posts, controller: "Public::PostsController"
end
resource :private_profile, controller: "Private::ProfileController" do
resources :posts, controller: "Private::PostsController"
end
无论您如何设置,您都可以轻松“知道”您嵌套在哪个资源中,因为您实际上将在特定于该嵌套的单独控制器中运行,因此可以为特定于该嵌套的逻辑提供一个完美的位置。对于一般逻辑,您会将其放入 parentPostsController
中。
你可以做到这一点的另一种方法是添加一个before_filter
喜欢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
不过我不喜欢这种方法。