微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

polymorphic-associations – Rails 3,Polymorphic Associations和No Route Matches

我已经学习Rails大约6周了,所以还是一个菜鸟!

我正在跟踪Ryan Bates关于多态关联的截屏视频,但在导航到/ model / xx / comments时我遇到了“No Route Matches”错误.

经过两天绕圈子,我完全被难倒了 – 一切似乎都到位了.

评论模型:

create_table "comments",:force => true do |t|
t.text     "content"
t.integer  "user_id"
t.integer  "commentable_id"
t.string   "commentable_type"
t.datetime "created_at"
t.datetime "updated_at"
end

评论类:

class Comment < ActiveRecord::Base
belongs_to :commentable,:polymorphic => true 
end

其他型号类:

class ModelName < ActiveRecord::Base
has_many :comments,:as => :commentable 
end

的routes.rb

resources :modelname,:has_many => :comments

comments_controller.rb

def index
@commentable = find_commentable  
@comments = @commentable.comments
end

private

  def find_commentable 
    params.each do |name,value|  
        if name =~ /(.+)_id$/  
            return $1.classify.constantize.find(value)  
        end  
    end  
    nil  
  end

这一切都根据教程,但仍然返回“没有路线匹配”.

我已尝试将路由的替代格式设置为嵌套资源.

resources :modelname do |modelname|
  modelname.resources :comments
end

在routes.rb中明确定义注释

resources :comments

以及routes.rb中的各种术语组合

resources :modelname,:has_many => :commentables

要么

resources :modelname,:has_many => :comments

要么

resources :modelname,:has_many => :comments,:through => :commentable

一切都没有成功.

有人遇到过这种情况么?我迷失在哪里开始寻找.

非常感谢

解决方法

如果您使用的是Rails 3,则路由选择会有所不同.您可以在模型中指定关系并在routes.rb中映射路由

在Rails 3的做事方式中,你的routes.rb应该有:

resources :model do
    resources :comments
 end

您不应该在路线中指定您的关系.刷新您的服务器,您应该获得/ model / id / comments / id之类的路由

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐