views:

41

answers:

2

I have a AudioFile that has_many photos. A photo has an attribute "primary" (0 or 1 in db) What is an idiomatic ruby way of doing something like this: I want to have a method on the AudioFile which returns the id of the primary photo, i.e the photo that has primary attribute set to true.

+1  A: 

I'm not sure if this is what you mean, but Enumerable#Select will give you all the items out of an enumerable object that match a case (given in a block).

Jeffrey Aylesworth
so I can write def primary_photo self.photos.select {|element| element.primary = 'true'} end
rordude
+1  A: 

Generally the best practice would be to set up a named_scope in your Photo model.

class Photo < ActiveRecord::Base
  named_scope :primary, :conditions => {:primary => true}
end

Then you can call the primary scope on your photos assocations. e.g.

@audio_file.photos.primary.first

You could also wrap this in a helper method.

def primary_photo
  photos.primary.first
end

See http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html for more details and examples or google named_scope.

samg