2012-07-31 136 views
21

我对自定义验证选项在Rails 3中的选择有些困惑,我希望有人能指点我可以帮助解决当前问题的资源。Rails 3 - 自定义验证

我目前有3个型号,vehicle,trimmodel_year。他们看起来如下:

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

我的查询是这样的 - 当我创建车辆时,如何确保所选的model_year对修剪有效(反之亦然)?

回答

56

您可以使用自定义的验证方法,如描述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 
24

可以使用ActiveModel::Validator类,像这样:

class VehicleValidator < ActiveModel::Validator 
    def validate(record) 
    return true if # custom model_year and trip logic 
    record.errors[:base] << # error message 
    end 
end 

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

    include ActiveModel::Validations 
    validates_with VehicleValidator 
end 
+4

这是从长远来看,更清洁。这应该是被接受的答案。 – kgpdeveloper 2014-08-17 07:05:47

+0

你应该把你的自定义验证器放在哪里?什么目录? – 2016-05-15 13:11:01

+0

我把它放在'lib/validators'中。我见过其他人把它放在'app/validators'中。随你便。只要确保将其添加到配置中的加载路径。 – uechan 2016-05-24 18:30:13