【问题标题】:Rails 3, Polymorphic Associations, and No Route MatchesRails 3、多态关联和无路由匹配
【发布时间】:2011-04-20 02:33:22
【问题描述】:

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

我正在关注 Ryan Bates 关于多态关联的截屏视频,但在导航到 /model/xx/cmets 时出现“无路由匹配”错误。

在这转了两天之后,我完全被难住了——一切似乎都到位了。

评论模型:

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

cmets_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 中显式定义 cmets

resources :comments

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

resources :modelname, :has_many => :commentables

resources :modelname, :has_many => :comments

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

都没有成功。

有没有其他人遇到过这种情况?我不知道从哪里开始寻找。

非常感谢

【问题讨论】:

    标签: polymorphic-associations ruby-on-rails-3


    【解决方案1】:

    如果您使用的是 Rails 3,路由的方式会有所不同。您在模型中指定关系并在 routes.rb 中映射您的路线

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

     resources :model do
        resources :comments
     end
    

    您不应该在路线中指定您的关系。刷新你的服务器,你应该得到一个类似 /model/id/cmets/id 的路由

    【讨论】:

    • 感谢您让我摆脱痛苦。简单但有效!
    • 我还想补充一点,我添加了一个嵌套路由并且遇到了同样的问题。然后,我重新启动服务器并开始工作。所以基本上,在正在运行的服务器上添加嵌套路由并不总是有效的。 :-) 重新启动它。
    【解决方案2】:

    在 Rails 3 中,情况有些不同。要获取 URL modelname/id/comments,您需要在 routes.rb 中包含以下路由:

    resources :modelname do
      resources :comments
    end
    

    请参阅this Rails Guide 了解更多信息,其中包含更多细节。

    【讨论】:

    • 当你知道怎么做时很容易!感谢您的指针和有用的链接,就像一个魅力。
    • 哈哈,一直都是这样的,对吧?很高兴能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    相关资源
    最近更新 更多