views:

29

answers:

2

I'm really really new to rails. I haven't really written any custom validation methods and I was wondering if one exists for this or if I should write my own.

I have a boolean value for images that says whether it's featured or not. How would I validate upon creating new entries and editing that there aren't more than a given number of featured photos? I'd want it to throw an error if I already have say, 10 photos flagged, and a user tries to flag another one. Thanks

+1  A: 
class Photo < ActiveRecord::Base

  validate :user_flaggings 

  def user_flaggings
    errors.add_to_base("type your error msg") if user.photos.count > 10 
  end

end

You can read more about custom validations here.

khelll
+3  A: 

Just a tweak on khelli's answer. A named_scope will make it a little cleaner.

class Photo < ActiveRecord::Base

named_scope :featured, :conditions => { :featured => true }

validate :user_flaggings

def user_flaggings
  errors.add_to_base("type your error msg") if Photo.featured.count > 10 && self.featured_changed? 
end

end

The featured_changed? check is to make sure the user was attempting to feature this image and it's not already a featured image.

Swards
+1 as I totally forgot about featured thingy!
khelll
There's a bug in this that I can't currently create any new featured photos if I already have 10 featured. I need a check to see if the one that we're adding isn't featured I guess
Stacia
khelll