0

我对 Rails 很陌生,并且在 Rails/ActiveRecord 似乎忽略validates_uniqueness_of了我继承的项目中声明的范围时遇到了麻烦。我有以下模型:

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

有一个现有的用户记录,其中一个emailoffoo@bar.com和一个brand_idof 1

尝试使用idof 123emailoffoo@bar.combrand_idof更新另一个用户记录时,2出现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;

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

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

4

2 回答 2

0

事实证明,这是 Devise 的“可验证”行为,它添加了它自己对电子邮件字段的独特验证。

于 2017-02-17T16:05:31.817 回答
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 >
于 2017-02-17T10:27:29.020 回答