2012-07-31 94 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