在同一个表rails模型中有两个字段的唯一性。

时间:2021-04-27 21:34:01

Is there a way to validate the uniqueness of two or more fields in the same model? For example lets say that I have fields :name and :zip. An acceptable set would be {[name1, zip1], [name1, zip2]}but you can't have {[name1,zip1],[name1,zip1]} in the same table.

是否有一种方法来验证同一个模型中两个或多个字段的唯一性?例如,假设我有字段:name和:zip。可以接受的集合是{[name1,zip1],[name1, zip2]},但是不能在同一个表中有{[name1,zip1],[name1,zip1]}。

Is there a rails validates method that can be used?

是否有可以使用的rails验证方法?

3 个解决方案

#1


2  

You should use scope:

您应该使用范围:

  validates_uniqueness_of :name, :scope => [:zip]

See documentation and guide for more information.

更多信息请参见文档和指南。

You can use :scope option to specify other attributes that are used to limit the uniqueness check.

您可以使用:scope选项来指定用于限制惟一性检查的其他属性。

#2


2  

You can do this using a validation like the others told you but you could also add an unique index to the table. That would prevent inserting duplicates on the database layer and increasre the select speed. You need to create a new migration for that rails g migration addUniqueIndexForZipAndNameToTablename

您可以像其他人告诉您的那样使用验证来实现这一点,但是您也可以向表添加一个惟一的索引。这样可以防止在数据库层插入重复,并增加选择速度。您需要为rails g迁移创建一个新的迁移

add_index :tablename, [:name, :zip], :unique => true

The only problem you might get is that there are MySQL Errors when you try to insert a duplicate you need to prevent that using

您可能会遇到的唯一问题是,当您试图插入一个副本时,会出现MySQL错误,您需要避免使用它

begin
  # insert,...
rescue ExceptionHere
  # do sth...
end

#3


2  

Another way

另一种方式

validates :name, :uniqueness => {:scope => [:zip]}

#1


2  

You should use scope:

您应该使用范围:

  validates_uniqueness_of :name, :scope => [:zip]

See documentation and guide for more information.

更多信息请参见文档和指南。

You can use :scope option to specify other attributes that are used to limit the uniqueness check.

您可以使用:scope选项来指定用于限制惟一性检查的其他属性。

#2


2  

You can do this using a validation like the others told you but you could also add an unique index to the table. That would prevent inserting duplicates on the database layer and increasre the select speed. You need to create a new migration for that rails g migration addUniqueIndexForZipAndNameToTablename

您可以像其他人告诉您的那样使用验证来实现这一点,但是您也可以向表添加一个惟一的索引。这样可以防止在数据库层插入重复,并增加选择速度。您需要为rails g迁移创建一个新的迁移

add_index :tablename, [:name, :zip], :unique => true

The only problem you might get is that there are MySQL Errors when you try to insert a duplicate you need to prevent that using

您可能会遇到的唯一问题是,当您试图插入一个副本时,会出现MySQL错误,您需要避免使用它

begin
  # insert,...
rescue ExceptionHere
  # do sth...
end

#3


2  

Another way

另一种方式

validates :name, :uniqueness => {:scope => [:zip]}