Reputation: 1202
My scenario: Movies have reviews, reviews have comments.
Movie model:
has_many :reviews
Review model:
has_many :comments
belongs_to :movie
Comment model:
belongs_to :review
Routes:
resources :movies do
resources :reviews do
resources :comments
end
end
Comments controller:
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
Comment view:
<%= 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 %>
The error that I get is:
NoMethodError (undefined method `comments' for #<ActiveRecord::Relation:0x007ff5c5870010>):
app/controllers/comments_controller.rb:5:in `create'
Can somebody please tell me what I'm doing wrong?
Thanks in advance..
Upvotes: 0
Views: 84
Reputation: 23770
Review.where
returns a list of reviews, what you want is an instance
@review = Review.where(:movie_id => @movie.id).first
or
@review = Review.find_by_movie_id(@movie.id)
Make sure to handle nil
case.
Upvotes: 2