0

ネストされたリソースへのコメントを許可しようとしていますが、[コメントの作成]ボタンを選択すると、app / controllers / comments_controller.rb:7:in `create'の#に対して未定義のメソッド'comment'が表示されます。私はまだrubyと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 %>
4

1 に答える 1

0

createステートメントの最初の行で次のことを行う必要があります

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'    

サイトの残りの部分は次のようになります

コメント_controller.rb

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

コメント.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

あなたはおそらくガイドのステップを逃しました。他のすべては大丈夫に見えます。

于 2013-01-14T07:46:39.473 に答える