嵌套的rails类和问题的麻烦路由

时间:2011-06-12 21:55:42

标签: ruby-on-rails routing nested-class

我试图在一段时间后回到轨道中,并且很难以嵌套的方式连接两个简单的脚手架构建的资源。父控制器工作,但孩子通常会爆炸。我一直在寻找这个问题的答案,但没有成功。

对于属于产品父级的特定评论子项,请路由“/ products / 1 / comments / 1”

错误消息

  

找不到没有ID的评论   app / controllers / comments_controller.rb:25:在'show'

     

参数:

     

{ “PRODUCT_ID”=> “中1”,   “ID”=> “中1”}

以下是comments_controller“show”

中的相关代码
def show
@product = Product.find(params[:product_id])
@comment = @product.comments.find(params[:comment_id])

(如果我将:comment_id更改为:id,则新错误为:)

  

无法找到ID = 1的评论[WHERE(comments。product_id = 1)]

     

{ “PRODUCT_ID”=> “中1”,   “ID”=> “中1”}

评论指数:/ products / 1 / comments

错误信息:

  

Fixnum:Class的未定义方法`model_name'   参数:   { “PRODUCT_ID”=> “中1”}

**索引视图中的相关代码**

18:     <td><%= link_to 'Show', [@product, comment.id] %></td>
19:     <td><%= link_to 'Edit', edit_product_comment_path(@product, comment) %></td>
20:     <td><%= link_to 'Destroy', [@product, comment], :confirm => 'Are you sure?',           :method => :delete %></td>

我花了几天时间搞乱这件事无济于事。检查简单的事情,例如:id to :(名词)_id以及在我的视图链接中切换[@product,comment]和[@product,comment.id]。

如何使这项工作受到高度赞赏。看起来它应该很简单,而且我几乎都遵循了“书”。这样做的问题在于我的rails文本(The Rails方式和一本带有几个章节的ruby介绍书)最多基于rails 2,并且Web资源尚未完全更新。

更新 * 的routes.rb *     Party2 :: Application.routes.draw做

resources :comments

resources :products do
  resources :comments
end

评论索引中的错误

  

Fixnum:Class

的未定义方法`model_name'

评论索引的相关代码(第18行的错误)

18:     <td><%= link_to 'Show', [@product, comment.id] %></td>
19:     <td><%= link_to 'Edit', edit_product_comment_path(@product, comment) %></td>
20:     <td><%= link_to 'Destroy', [@product, comment], :confirm => 'Are you sure?', :method => :delete %></td>

另一次更新: * 模型 *

class Product < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :product
end

再次感谢,

卡梅伦

(对我来说这似乎不太常见,因为我一直在关注教程。:/)

1 个答案:

答案 0 :(得分:0)

如果评论只能属于一个产品,那么您应该可以在comments_controller.rb中执行以下操作:

def show
  @comment = Comment.find(params[:id])
  # @product = @comment.product
end
相关问题