将资源嵌套在单一资源中

时间:2012-11-15 00:23:26

标签: ruby-on-rails ruby-on-rails-3 rails-routing

考虑以下路线:

resource :public_profile do
  resources :posts
end

resource :private_profile do
  resources :posts
end

我如何在PostsController中确定我嵌套在哪个奇异资源中?

2 个答案:

答案 0 :(得分:0)

您可以将它们路由到不同的控制器(通过在路由中指定),这些控制器是从相同的“基础”控制器PostsController扩展的。在扩展控制器中你 识别它们:

EX:

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操作中

答案 1 :(得分:0)

你可以做到这一点的一种方法是创建另外两个控制器,扩展一些主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

无论你如何设置它,你都可以很容易地“知道”你嵌套在哪个资源中,因为你实际上是在一个特定于该嵌套的独立控制器中运行,因此可以拥有一个特定逻辑的完美位置。那个筑巢。对于一般逻辑,您可以将其放入父PostsController


另一种方法是将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

我不关心这种做法。