Ruby-on-rails Rails 3 - 自定义验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11736786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:47:05  来源:igfitidea点击:

Rails 3 - Custom Validation

ruby-on-railsruby-on-rails-3activerecord

提问by H O

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.

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

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

我目前有 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

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)?

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

回答by davidrac

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

回答by Andrew Nesbitt

You can use the ActiveModel::Validatorclass like so:

您可以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