开发者

Trouble with nested rails classes & routing

I'm trying to get back into rails after a while and am having a tough time connecting two simple scaffold-built resources in a nested fashion. The parent controller works, but the child usually blows up. I've been looking all over for an answer to this problem, but haven't succeeded.

For a specific comment child belonging to a product parent, route "/products/1/comments/1"

Error message

Couldn't find Comment without an ID app/controllers/comments_controller.rb:25:in `show'

Parameters:

{"product_id"=>"1", "id"=>"1"}

Here's the relevant code from comments_controller "show"

def show
@product = Product.find(params[:product_id])
@comment = @product.comments.find(params[:comment_id])

(If I change :comment_id to just :id the new error is:)

Couldn't find Comment with ID=1 [WHERE (comments.product_id = 1)]

{"product_id"=>"1", "id"=>"1"}

For comment index: /products/1/comments

Error info:

undefined method `model_name' for Fixnum:Class Parameters: {"product_id"=>"1"}

** Relevant code from index view **

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>

I've spent a couple days messing with this to no avail. Been checking simple things like :id to :(noun)_id as well as switching between [@product, comment] and [@product, comment.id] in my view links.

Any suggestions are greatly appreciated on how to get this working. It seems like it should be simple, and I pretty much followed the "book." The trouble with this is that my rails texts (The Rails way and a little ruby intro book with a couple chapters on rails) are based on rails 2 at best, and web resources haven't been entirely updated.

Updates: *Routes.rb* Party2::Application.routes.draw do

resources :comments

resources :products do
  resources :comments
end

Errors from comment index

undefined method `model_name' for Fixnum:Class

Relevant code from comment index (Error at line 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>

Another update: *Models*

class Product < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :product
end

Thanks again,

Cameron

(Seems very strange to me that 开发者_运维百科this shouldn't work, as I've been following tutorials. :/)


If a comment can belong to only one product, you should be able to do something like this in the comments_controller.rb:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜