views:

40

answers:

1

Given this:

class User < ActiveRecord::Base
  has_many :photos
  MAX_PHOTOS = 5
  validate :quantity_of_photos

  def quantity_of_photos
    ???
  end
end

And this:

@user.photos.size  # => 5

I need this to fail:

@user.photos << Photo.create(valid_photo_attributes)

How do I do this validation?

+2  A: 

Move the quantity of photos method to the Photo model:

class Photo < ActiveRecord::Base

   belongs_to :user
   validates :quantity_of_photos

    def quantity_of_photos
      if new_record? && user.photos.size >= User::MAX_PHOTOS
        errors.add_to_base "You cannot have more than #{MAX_PHOTOS} photos."
      end
    end

end

The validity of a ActiveRecord instance is determined by whether there are errors in it's errors array.

Ben
Your method results in @user failing validation, but that's not quite it. I need this <code>@user.photos << Photo.create(valid_photo_attributes)</code> to produce an error. Otherwise, Photos can be associated successfully to Members until, at some point later in the code, a validation occurs. Better they can't be associated in the first place.
Gavin
Ok, edited to answer your question better
Ben
This would do it, but it's poor design. It requires Photo to know what's going on with a Member and any other model that has photos and needs similar validation.
Gavin