嵌套轨道类和路由的问题



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

对于属于产品父级的特定注释子级,请发送"/products/1/comments/1"

错误消息

找不到没有ID的评论app/controllers/comments_controller.rb:25:在"显示"中

参数:

{"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到:(名词)_id,以及在我的视图链接中在[@product,comment]和[@product,comment.id]之间切换。

我们非常感谢您对如何实现这一目标提出的任何建议。它看起来应该很简单,我几乎遵循了"书"。问题是,我的rails文本(the rails way和一本关于rails的小ruby介绍书)充其量是基于rails 2的,并且web资源还没有完全更新。

更新:*路线.rb*第2部分::Application.routes.draw do

resources :comments
resources :products do
  resources :comments
end

注释索引中的错误

Fixnum的未定义方法"model_name":Class

注释索引中的相关代码(第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

再次感谢

Cameron

(这对我来说似乎很奇怪,因为我一直在学习教程。:/)

如果一个注释只能属于一个产品,那么您应该能够在comments_controller.rb:中执行这样的操作

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

最新更新