views:

21

answers:

2

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...

A: 

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.

Karl
thanks, is method chaining bad? because it looks confusing?
raphael_turtle
Not at all, it's very useful. Just remember that Ruby evaluates from left to right, for example `"123".to_i.to_s.size` will convert "123" first to an Integer, then back to a String, then return the size of the string (which is 3). You just need to be careful when chaining methods on when the method return value might be nil.
Karl
A: 

It would be better to define in Photo Model if gallery is complesery for photo "validate_presece_of :gallery_id " Then this problem would not be occur .