Rails validates_uniqueness_of忽略范围

时间:2017-02-17 10:01:38

标签: ruby-on-rails activerecord validates-uniqueness-of

我是Rails的新手,我在Rails / ActiveRecord上遇到麻烦,似乎忽略了我继承的项目中validates_uniqueness_of声明的范围。我有以下型号:

class User < ActiveRecord::Base
  …
  validates_uniqueness_of :email, scope: :brand_id, allow_nil: true
  …
  belongs_to :brand
  …
end

现有用户记录的email foo@bar.combrand_id 1

尝试更新id 123 email foo@bar.com brand_id2 Validation failed: Email has already been taken的其他用户记录时,我得到SELECT 1 AS one FROM "users" WHERE ("users"."email" = 'foo@bar.com' AND "users"."id" != 123) LIMIT 1; SELECT 1 AS one FROM "users" WHERE ("users"."email" = 'foo@bar.com' AND "users"."id" != 123 AND "users"."brand_id" = 2) LIMIT 1; 错误。

当发生此错误时,我看到以下两个查询一个接一个地运行:

'angular2-ui-switch': 'npm:angular2-ui-switch'

看起来第二个查询正在执行正确的唯一性检查,但第一个查询忽略了范围。

有关如何查看或如何进一步调试的任何提示将不胜感激。

2 个答案:

答案 0 :(得分:0)

模型中的逻辑没有任何问题。还有其他东西可以阻止记录保存。

你能把整个模型?

class Artwork < ApplicationRecord

  ...

  validates_uniqueness_of :artwork_file_name, scope: :game_id

  ...

end


2.3.1 :810 > Artwork.new(artwork_file_name: 'asd', game_id: 100).save
   (12.5ms)  BEGIN
  Artwork Exists (92.1ms)  SELECT  1 AS one FROM `artworks` WHERE `artworks`.`artwork_file_name` = BINARY 'asd' AND `artworks`.`game_id` = 100 LIMIT 1
  SQL (64.1ms)  INSERT INTO `artworks` (`game_id`, `artwork_file_name`, `created_at`, `updated_at`) VALUES (100, 'asd', '2017-02-17 10:25:25', '2017-02-17 10:25:25')
   (17.9ms)  COMMIT
 => true
2.3.1 :811 > Artwork.new(artwork_file_name: 'asd', game_id: 100).save
   (0.2ms)  BEGIN
  Artwork Exists (0.5ms)  SELECT  1 AS one FROM `artworks` WHERE `artworks`.`artwork_file_name` = BINARY 'asd' AND `artworks`.`game_id` = 100 LIMIT 1
   (6.1ms)  ROLLBACK
 => false
2.3.1 :812 > Artwork.new(artwork_file_name: 'asd', game_id: 101).save
   (0.2ms)  BEGIN
  Artwork Exists (45.4ms)  SELECT  1 AS one FROM `artworks` WHERE `artworks`.`artwork_file_name` = BINARY 'asd' AND `artworks`.`game_id` = 101 LIMIT 1
  SQL (6.7ms)  INSERT INTO `artworks` (`game_id`, `artwork_file_name`, `created_at`, `updated_at`) VALUES (101, 'asd', '2017-02-17 10:26:05', '2017-02-17 10:26:05')
   (6.3ms)  COMMIT
 => true
2.3.1 :813 >

答案 1 :(得分:0)

原来是Devise&#34;有效的&#34;行为,增加了它自己对电子邮件字段的唯一验证。