2013-01-14 59 views
0

我想在嵌套的资源上允许评论,我得到了一个未定义的方法'评论'在app/controllers/comments_controller.rb中:#:在'创建'当我选择创建评论按钮。由于我对ruby和rails还不熟悉,因此我遵循入门指南中的代码,并且似乎无法找出错误的原因。Rails嵌套资源未定义的博客文章的方法

关联是:

has_many :comments 
belongs_to :restaurant 

在我的路线

resources :restaurants do 
    resources :comments 
end 

在评论控制器

def create 
    @restaurant = Restaurant.find(params[:restaurant_id]) 
    @comment = @restaurant.comments.create(params[:comment]) 
    redirect_to restaurant_path 
end 

在我的餐厅秀模板

<%= form_for([@restaurant, @restaurant.comments.build]) do |f| %> 
<h2>Add a comment</h2> 
    <div> 
    <%= f.text_area :body %> 
    </div> 
    <div> 
    <%= f.submit %> 
<% end %> 
+0

“comments_controller”的第7行是什么?我没有在任何地方看到任何引用单数的“评论”方法。 –

+0

您的路线在创建操作结束时不正确,请试用restaurant_path(@restaurant) – siekfried

+0

谢谢大家。我仍然不知道我错过了什么,但是我删除了代码,从头开始工作。 – Ria

回答

0

你应该做的第一线以下在创建语句

raise params.to_yaml 

你应该看到你的网站的以下

utf8: ✓ 
authenticity_token: ... 
comment: !ruby/hash:ActiveSupport::HashWithIndifferentAccess 
    commenter: Test Commenter 
    body: Test Comment 
commit: Create Comment 
action: create 
controller: comments 
restaurant_id: '1'  

其余部分应该看起来像下面

comments_controller.rb

def create 
    @restaurant = Restaurant.find(params[:restaurant_id]) 
    @comment = @restaurant.comments.create(params[:comment]) 
    redirect_to restaurant_path(@restaurant) 
end 

comments.rb

class Comment < ActiveRecord::Base 
has_many :comments 
belongs_to :restaurant 
end 

restaurants.rb

class Restaurant < ActiveRecord::Base 
attr_accessible :content, :name, :title 
has_many :comments 
end 

你可能错过了在引导的一个步骤。其他一切看起来都没问题。

+0

感谢您的帮助。实际上我看了一下railscasts 196,但这不是我正在寻找的内容,或者我不清楚如何根据需要对其进行编辑。上面的插曲和示例将创建一个嵌套表单,用于添加新的餐厅个人资料和新评论。我只想在现有的餐厅简介上留言。我按照入门指南代码了解如何执行此操作。除非代码已经过时,否则我看不出有什么问题。 – Ria

+0

请重新检查我的答案。 –