Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - Custom Validation

I'm somewhat confused by my options for custom validations in Rails 3, and i'm hoping that someone can point me in the direction of a resource that can help with my current issue.

I currently have 3 models, vehicle, trim and model_year. They look as follows:

class Vehicle < ActiveRecord::Base
  attr_accessible :make_id, :model_id, :trim_id, :model_year_id
  belongs_to :trim
  belongs_to :model_year
end

class ModelYear < ActiveRecord::Base attr_accessible :value has_many :model_year_trims has_many :trims, :through => :model_year_trims end

class Trim < ActiveRecord::Base attr_accessible :value, :model_id has_many :vehicles has_many :model_year_trims has_many :model_years, :through => :model_year_trims end

My query is this - when I am creating a vehicle, how can I ensure that the model_year that is selected is valid for the trim (and vice versa)?

like image 801
Harry Avatar asked Sep 07 '25 13:09

Harry


1 Answers

you can use custom validation method, as described here:

class Vehicle < ActiveRecord::Base
  validate :model_year_valid_for_trim

  def model_year_valid_for_trim
    if #some validation code for model year and trim
      errors.add(:model_years, "some error")
    end
  end

end
like image 137
davidrac Avatar answered Sep 09 '25 02:09

davidrac