简体   繁体   English

如何验证关联的模型?

[英]How can I validate an associated model?

Is my first time building a custom validation , since trying to the regular ORM validations did not work. 我是第一次构建自定义验证,因为尝试常规的ORM验证无效。 I have a model called AdGroup which belongs to another model called Car. 我有一个名为AdGroup的模型,该模型属于另一个名为Car的模型。 I want to send prevent that a user creates a new Ad Group if they have not selected a car. 我希望避免用户未选择汽车的情况下创建新的广告组。 Also the Car is a file. 而且Car是文件。

class AdGroup < ActiveRecord::Base
  belongs_to :car
  validate :validate_car_id

  def validate_car_id
    car = Car.find_by(id: params[:id])
    if car.nil?
      errors.add(:car, "Select a car image")
    end
  end
end

class Car < ActiveRecord::Base
  validates :make, :model, :year, presence: true                  
  validates :file, presence: true
  belongs_to :make
  has_many :ad_groups

  ...
end

Is an image that I am trying to select . 是我要选择的图像。

Your Ad Group model needs to be associated with the Car model. 您的广告组模型需要与Car模型相关联。 AdGroup models should have belongs_to :car line and the Car model needs has_many :ad_groups . 广告组模型应具有belongs_to :car行,汽车模型需要has_many :ad_groups

To validate associated models you could use ActiveRecord's validates_associated . 要验证关联的模型,可以使用ActiveRecord的validates_associated Be sure to read the docs by the link for gotchas. 请务必阅读有关陷阱的链接的文档。

class AdGroup < ActiveRecord::Base
  belongs_to :car

  validates :car, presence: true
  validates_associated :car
end

When using validates_associated you don't have to do custom validation. 使用validates_associated您不必进行自定义验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM