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

Thanks

Answers


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.

For example:

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.


Need Your Help

Does MacRuby support static compilation?

static compilation macruby macrubyc

Does the latest version of MacRuby support static compilation?

Questions about JSON.stringify in ECMAScript

javascript json ecmascript-5 stringify

I'm watching MDN's "Using native JSON". And I've 3 questions about the JSON.stringify method.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.