Where to perform validation
If I have two models, and am using accepts_nested_attributes_for where should I be putting my validations for the child model.
For example; if I want to validate the images size and limit (ie only allow the user to upload 3 images) should I be validating in the Animal or AnimalImage model
class Animal < ActiveRecord::Base has_many :animal_images, dependent: :destroy accepts_nested_attributes_for :animal_images, allow_destroy: :true end class AnimalImage < ActiveRecord::Base mount_uploader :image, AnimalImageUploader belongs_to :animal end
I am using carrierwave to upload my images. I have noticed they have some built in helper methods but from the examples I have seen the image is always in the parent model (ie a user having an avatar)
Any help appreciated
If you want to limit the number of images per Animal, you have to add this validation to the Animal model. If you want to validate something on individual images (e.g. file type, size, etc.) then these go to the AnimalImage model.
class Animal validate :limit_num_of_images def limit_num_of_images errors.add(:animal_images, :less_than_or_equal_to, count: 3) if animal_images.size > 3 end end
This example is very simplistic but it should get you started. One thing missing for example, is any checks about valid images. You might want to only take into account the number of valid images.