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之类的路由

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...