Reputation: 5197
country
attribute's default value is nil.
In countries table, some record has image_url
, and the rest of the record's country
attributes are nil.
So I coded this in helper
def image(user)
if user.country.image_url
image_tag "flags/#{user.country.image_url}.png"
end
end
However, it returns error when image_url
was nil
Something went wrong
How can I fix?
Upvotes: 0
Views: 98
Reputation: 6346
While method chaining like that certainly works, your code will look a lot cleaner and become less coupled if you implement some method delegation.
Inside of your User model:
class User < ActiveRecord::Base
belongs_to :country
delegate :image_url, :to => :country, :prefix => true, :allow_nil => true
end
Now your helper becomes simply:
def image(user)
if user.country_image_url
image_tag "flags/#{user.country_image_url}.png"
end
end
Law of Demeter states:
Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
Also check out Rail Best Practices Law of Demeter; if nothing else you're saving yourself the extra clause in your if statement & your code looks pretty.
Upvotes: 3
Reputation: 14619
You'll need two conditions: The user has to have a country, and that country has to have an image_url. Only then will there be something to show. Luckily, it's a simple tweak:
def image(user)
if(user.country && user.country.image_url)
image_tag "flags/#{user.country.image_url}.png"
end
end
If you're paranoid, you should make sure that user
isn't nil
either.
Hope that helps!
Upvotes: 3