1

I have a model User which has one to many relation to the Image model.

How can I limit user to be able to store only 3 images?

fotanus
  • 19,618
  • 13
  • 77
  • 111
London
  • 14,986
  • 35
  • 106
  • 147
  • 2
    By adding a custom validator. Have a look at the guides, http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations – pdu Oct 21 '13 at 11:24
  • Some related answers here: http://stackoverflow.com/questions/2263267/limit-number-of-objects-in-has-many-association – Thomas Klemm Oct 21 '13 at 11:56

1 Answers1

1

How about validation?

class Image
  belongs_to :user

  validate :max_3_per_user
  # (...)
  private

  def max_3_per_user
    if user_id && Image.where(user_id: user_id).count >= 3
      errors.add(:images, 'There can only be 3 per user')
    end
  end
end
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91