Reputation: 16316
Forgive me if this is a basic question; I'm learning Rails (using 3.2) as I go.
My Event
model has_many
images
. Each image has an is_primary
boolean field. Event
should have a cover_image
method, which returns the image with is_primary
set to true, or the first image otherwise. This is my code:
def cover_image
imgs = self.images
imgs.each { |i| return i if i.is_primary }
# If no primary
return imgs.first
end
I can't help feeling like there's a better way to do it, one that doesn't involve looping through all the elements just to find one.
Upvotes: 1
Views: 338
Reputation: 14048
You could do this with a scope quite easily:
Image model
scope :primary, where(:is_primary => true)
Event model
def cover_image
images.primary.first
end
This is a really basic example that should get you started at least, you'll want to build on it to handle a missing primary image gracefully, for example.
For completeness, you don't have to do this as a scope, if you'd prefer you can use where statements directly. Scopes are just really nice for staying DRY:
Event model
def cover_image
images.where(:is_primary => true).first
end
Upvotes: 4