Rails: Validating uniqueness across multiple model

2019-05-22 23:53发布

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.

2条回答
我命由我不由天
2楼-- · 2019-05-23 00:30

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
查看更多
等我变得足够好
3楼-- · 2019-05-23 00:52

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 ?

查看更多
登录 后发表回答