Rails:验证多个模型之间的唯一性 [英] Rails: Validating uniqueness across multiple models

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

问题描述

是否有一种方法可以验证两个不同模型中的列之间的属性的唯一性.例如:

Is there a way to validate the uniqueness of an attribute among columns in two different models. For example:

我有一个自行车模型和一个汽车模型.创建新的自行车时,我想确认该自行车的名称是唯一的,因为没有其他自行车或具有该名称的汽车.我不想将它们放到一个模型中,因为它们具有截然不同的属性.我在轨道上2.3.8

I have a bike model and a car model. When I create a new bike, I want to validate that the name of the bike is unique in that there is no other bike or car with that name. I don't want to put these into one model because they have vastly different properties. I'm on rails 2.3.8

谢谢.

推荐答案

Rails不会自动跨模型验证(无论如何,我也不认为).您可能应该只编写自己的检查方法,等等...

Rails doesn't validate across models (I don't think, anyways) automatically. You should probably just write your own method to check, a la…

class YourModel < ActiveRecord::Base
  validates :uniqueness_of_a_property_across_models

  def uniqueness_of_a_property_across_models
    // check the other model
  end
end

这篇关于Rails:验证多个模型之间的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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