2017-02-17 117 views
0

我對Rails很陌生,在Rails/ActiveRecord中遇到問題,看起來忽略了我繼承的項目中的validates_uniqueness_of聲明的範圍。我有以下型號:Rails validates_uniqueness_of忽略範圍

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

有與[email protected]email1一個brand_id現有用戶記錄。

當試圖更新的123id其他用戶紀錄,[email protected]email2一個brand_id,我得到一個Validation failed: Email has already been taken錯誤。

我看到下面的兩個查詢運行一前一後出現此錯誤:

SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[email protected]' AND "users"."id" != 123) LIMIT 1; 
SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[email protected]' AND "users"."id" != 123 AND "users"."brand_id" = 2) LIMIT 1; 

它看起來像第二個查詢是做正確的唯一性檢查,但第一個被忽略的範圍。

任何提示什麼看或如何進一步調試將不勝感激。

回答

0

模型中的邏輯沒有任何問題。還有其他的東西會阻止Record保存。

你可以把整個模型?

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 > 
+0

我追蹤到設計驗證電子郵件是唯一的。 –

0

它原來是設計的「可驗證」的行爲,它增加了它自己的電子郵件領域的獨特驗證。