0

我的场景:电影有评论,评论有评论。

电影型号:

has_many :reviews

审查模型:

has_many :comments
belongs_to :movie

评论型号:

belongs_to :review

路线:

resources :movies do
  resources :reviews do
    resources :comments
  end
end

评论控制器:

def create
  @movie = Movie.find(params[:movie_id])
  @review = Review.where(:movie_id => @movie.id)
  @comment = @review.comments.create(params[:comment])  // Line 5
  redirect_to movie_path(@movie)
end

评论视图:

<%= form_for([@movie, r, r.comments.build]) do |f| %>
  <div class="field">
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit "Submit" %>
  </div>
<% end %>

我得到的错误是:

NoMethodError (undefined method `comments' for #<ActiveRecord::Relation:0x007ff5c5870010>):
app/controllers/comments_controller.rb:5:in `create'

有人可以告诉我我做错了什么吗?

提前致谢..

4

1 回答 1

2

Review.where返回评论列表,你想要的是一个实例

@review = Review.where(:movie_id => @movie.id).first

或者

@review = Review.find_by_movie_id(@movie.id)

确保处理nil案件。

于 2011-12-14T10:42:27.947 回答