25

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

我目前有 3 个模型vehicletrimmodel_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 对装饰有效(反之亦然)?

4

2 回答 2

63

您可以使用自定义验证方法,如此所述:

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
于 2012-07-31T09:42:19.833 回答
28

您可以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
于 2012-07-31T09:44:58.677 回答