【问题标题】:Change param name to nested resource parent将参数名称更改为嵌套资源父级
【发布时间】:2010-06-06 10:19:05
【问题描述】:

我有这条路线:

resources :tags do
      resources :comments
end

所以 cmets 的 :create 操作具有以下形式

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

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

【问题讨论】:

  • 以下解决方案有什么问题?

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


【解决方案1】:
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

把它放在你的控制器中

【讨论】:

    【解决方案2】:

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

    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"}
    

    【讨论】:

    • 我认为将资源名称定义为模型名称以外的其他名称的问题是多态 url 方法将失败。至少这是我的经验。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多