将param名称更改为嵌套资源父级

时间:2010-06-06 10:19:05

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

我有这条路线:

resources :tags do
      resources :comments
end

因此评论的:create操作具有以下形式

tag_comments POST   /tags/:tag_id/comments(.:format)

如何将参数名称从:tag_id更改为:commentable_id

2 个答案:

答案 0 :(得分:2)

map.tags do
  resources :comments, :path_prefix => '/tags/:commentable_id'
end

或通过before_filter

before_filter :tag2commentable

private
def tag2commentable
  params[:commentable_id] = params[:tag_id] unless params[:tag_id].blank?
end

把它放在你的控制器中

答案 1 :(得分:1)

其中一个可能是你想要的:

map.resources :commentables, :as => "tags", :collection => :comments
map.resources :commentables, :as => "tags", :has_many => :comments

我认为后者是正确的,这可以解决:

$ rake routes
commentable_comments GET /tags/:commentable_id/comments(.:format) {:action=>"index", :controller=>"comments"}
...

但我认为你的模特关系可能会被某种方式搞砸,因为这没有任何意义。请注意修改帖子并添加有关模型关系的信息吗?

我想有

map.resources :commentables, :has_many => :tags

map.resources :taggables, :has_many => :comments

会更有意义:

 commentable_tags GET /commentables/:commentable_id/tags(.:format) {:action=>"index", :controller=>"tags"}
taggable_comments GET /taggables/:taggable_id/comments(.:format)   {:action=>"index", :controller=>"comments"}