Rails: Validating uniqueness across multiple models

爱⌒轻易说出口 提交于 2019-12-10 10:36:29

问题


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

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

Thanks.


回答1:


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



回答2:


Maybe your Car and Bike Models can have somes common properties like this name, and they can both inherit a common model, and have your uniqueness validation on this model ?



来源:https://stackoverflow.com/questions/4676371/rails-validating-uniqueness-across-multiple-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!