Rails 3-自定义验证 [英] Rails 3 - Custom Validation

查看:68
本文介绍了Rails 3-自定义验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我目前有3种车型,车辆修剪 model_year 。它们如下所示:

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
end

类ModelYear< ActiveRecord :: Base
attr_accessible:值
has_many:model_year_trims
has_many:trims,:through =>:model_year_trims
end

class ModelYear < ActiveRecord::Base attr_accessible :value has_many :model_year_trims has_many :trims, :through => :model_year_trims end

Trim< ActiveRecord :: Base
attr_accessible:value,:model_id
has_many:车辆
has_many:model_year_trims
has_many:model_years,: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是否选择了对修剪有效的对象(反之亦然)?

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

这篇关于Rails 3-自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆