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 endclass 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)?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With