raphael_turtle
raphael_turtle

Reputation: 7314

Undefined method for nil:NilClass on an association view

Gallery has_many photos. Photos belongs_to gallery

In my photo 'show' view I get the error 'undefined method `name' for nil:NilClass' for the line

<%= @photo.gallery.name %>

the error only appears on photos that aren't part of a gallery (that don't have a gallery name assigned to them) the ones that do, appear as expected i.e the gallery name is shown that it belongs to. The api says "Ruby raises NoMethodError if you invoke a method on an object that does not respond to it" but shouldn't the photo object respond to gallery.name even though it's empty?? as the models are properly associated...

Upvotes: 1

Views: 3487

Answers (2)

user386660
user386660

Reputation: 501

It would be better to define in Photo Model if gallery is compulsory for photo.

validate_presence_of :gallery_id

Then this problem would not be occur .

Upvotes: 0

Karl
Karl

Reputation: 6165

You may not realize it, but you are doing method chaining.

@photo.gallery returns the Gallery object associated with the Photo. @photo.gallery.name returns the name associated with the Gallery object associated with the Photo.

Might be easier to think of this as (@photo.gallery).name

The following is equivalent to your code:

<% @gallery = @photo.gallery %>
<%= @gallery.name %>

In your case, when a photo has no gallery, @photo.gallery returns nil. You simply need to check for this:

<%= @photo.gallery.name unless @photo.gallery.nil? %>

Or have an alternate case for when it doesn't exist, whatever you want.

Upvotes: 4

Related Questions