Justin Meltzer
Justin Meltzer

Reputation: 13548

Ruby on Rails: undefined method in my view partial

I get this error: undefined method 'vote_sum' for nil:NilClass

for this line in my view partial: <p id='votes'><%= pluralize @video.vote_sum, 'Votes' %></p>

I don't understand why since vote_sum is a column in the videos table. Here's some of the relevant logic in my Video model:

def vote_sum
  read_attribute(:vote_sum) || video_votes.sum(:value)
end

and my VideoVote model:

after_create :update_vote_sum

private

  def update_vote_sum
    video.update_attributes(:vote_sum => video.vote_sum + value)
  end

Any understanding of why @video.vote_sum is undefined in my view partial?

UPDATE:

Here's the relevant code in the create method of my video_votes controller:

  @video = Video.find(params[:video_vote][:video_id])
  @vote = @video.video_votes.new 

Upvotes: 0

Views: 3522

Answers (1)

Mike Lewis
Mike Lewis

Reputation: 64137

It is saying vote_sum is an undefined method because it isn't calling it on a video, it is actually calling it on Nil. This is happening because @video is nil, rather than being an instance of Video.

The problem is that @video isn't being set properly in your controller.

I think you want

@video = Video.find(params[:video_id]) 

assuming params[:video_id] exists.

Edit

It seems as though you have a list of videos you want to show a partial for, and rails provides a mechinism for showing a collection of partials.

<%= render @videos %> # assuming you have a partial called _video.html.erb

To access the video, you access it using the video variable in _video.html.erb

See here for more.

Upvotes: 1

Related Questions