我已经学习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之类的路由