Ruby on rails 获取与标准嵌套资源不同的内容
我想知道是否有可能以不同于我通常看到的方式嵌套资源 通常,资源是这样的:Ruby on rails 获取与标准嵌套资源不同的内容,ruby-on-rails,Ruby On Rails,我想知道是否有可能以不同于我通常看到的方式嵌套资源 通常,资源是这样的: resources :article do resources :comment end scope "/benefits" do resources :company_benefit_types end 这将生成URL/article/:article_id/comment[当然是评论索引] 然而,我想知道我是否可以用不同的方式来获得类似的东西 /article/comment [excluding
resources :article do
resources :comment
end
scope "/benefits" do
resources :company_benefit_types
end
这将生成URL/article/:article_id/comment
[当然是评论索引]
然而,我想知道我是否可以用不同的方式来获得类似的东西
/article/comment [excluding :article_id]
文章将具有所有其他正常路径,注释的行为将与第一个示例中的行为相同。有没有办法做到这一点,以便我可以保持/comment与comments\u controller的连接,或者我需要将所有的comment方法重新定位到articles\u controller中?我更愿意避免这种情况,因为它会在以后引起头痛
**你可能会问我为什么要在这种情况下这么做。事实是,我是在不同的背景下做的,但这一点更容易解释
编辑:
真正的目的与示例不同。我想要一名“员工福利”控制员,成为一名定期控制员并拥有定期资源。但是,我希望能够做一些像/employee\u benefits/new\u type这样的事情。福利类型是在创建新员工福利时出现在表单中的内容。我希望能够执行诸如/employee\u benefits/edit\u type[:id]、/employee\u benefits/delete[不完全是这样]
我认为名称空间是一种方式,但我不完全确定如何做到这一点
更多编辑:
我目前正在使用这些资源:
match '/benefits/new_type' => 'company_benefits#new_type'
match '/benefits/create_type' => 'company_benefits#create_type'
match '/benefits/types' => 'company_benefits#types'
match '/benefits/type' => 'company_benefits#types'
而不是
resources :company_benefits, :path => '/benefits', :as => :benefits do
<not using this line of code>
resources :company_benefit_types
</not using this line of code>
end
resources:company\u benefits,:path=>'/benefits',:as=>:benefits do
资源:公司\福利\类型
结束
这应该对您有所帮助(请注意,我省略了复数“s”):
实际上,您在上面写的内容将生成
articles/:article\u id/comments
您可以查看名称空间示例,基本上在注释路径前面加上“/article”。这将创建您想要的路线-尽管我鼓励您考虑一下,并确保删除文章id是您想要的
浅嵌套也可能对您很好-
编辑:
听起来你想要的东西在rails 2中是这样的:
resources :company_benefit_types, :path_prefix => "/benefits"
在rails 3中,它将如下所示:
resources :article do
resources :comment
end
scope "/benefits" do
resources :company_benefit_types
end
通过运行bundle exec rake routes
检查输出,查看其外观
company_benefit_types GET /benefits/company_benefit_types(.:format) company_benefit_types#index
POST /benefits/company_benefit_types(.:format) company_benefit_types#create
new_company_benefit_type GET /benefits/company_benefit_types/new(.:format) company_benefit_types#new
edit_company_benefit_type GET /benefits/company_benefit_types/:id/edit(.:format) company_benefit_types#edit
company_benefit_type GET /benefits/company_benefit_types/:id(.:format) company_benefit_types#show
PUT /benefits/company_benefit_types/:id(.:format) company_benefit_types#update
DELETE /benefits/company_benefit_types/:id(.:format) company_benefit_types#destroy
是否有多篇
文章
?如果是这样的话,你怎么知道该显示哪个评论呢;在不知道您引用的是哪篇文章的情况下,您会显示哪些评论?是的,有不止一篇文章。其目的是创建文章的“类型”或“类别”。创建文章时,表单提供选择类型的选项。我希望类型是预先制作的,这是允许您预先制作类型的功能。您是说“评论”是文章的类型,而不是一篇文章有很多评论?您将如何区分有效ID和类型?你可以通过路由机制来实现,但在我看来,这已经开始变得太“诡计”了。你为什么要这样做?事实上,这对我来说很有意义。在仍然使用资源而不是匹配项的情况下,有没有办法做到这一点?是的,好问题。我已经更新了我的答案,以显示这将如何工作。