Undefined method for nil:NilClass on an association view
Gallery h开发者_如何学Pythonas_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...
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.
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 .
精彩评论