2013-05-20 33 views
0

在我的一個模型中,我定義了相等也可以使用字符串和符號。角色是等於另一個角色(或字符串或符號),如果它的name屬性是一樣的:在has_many關係中,在返回的集合中包含?不承認平等

class Role 
    def == other 
    other_name = case other 
       when Role then other.name 
       when String, Symbol then other.to_s 
       end 
    name == other_name 
    end 
end 

的平等檢查有效糾正:

role = Role.create name: 'admin' 
role == 'admin' # => true 
role == :admin # => true 

但是當我使用的Role模型一的has_many關係,收集我進不去,include?不認可這種平等:

user = User.create 
user.roles << role 
User.roles.include? role # => true 
User.roles.include? 'admin' # => false 
User.roles.include? :admin # => false 

爲了使這項工作,我必須明確地CONVER噸這對的數組:

User.roles.to_a.include? 'admin' # => true 
User.roles.to_a.include? :admin # => true 

因此很明顯的Rails覆蓋由user.roles返回的數組中的include?方法。這很糟糕,並且與Enumerable#include?(明確指出「EQUALTY使用==進行了測試」)的ruby specification相反。對於我從user.roles獲得的數組,這不是真的。 ==從未被稱爲。

include?指定的修改後的行爲在哪裏?

是否有另一種方法來測試我錯過了包含?或者我每次都必須使用to_aRole的實際實例嗎?

+0

這是什麼:'User.roles.class'在你的控制檯? –

+0

@grotori:user.roles.class#=>數組 – Conkerchen

回答

0

您沒有正確實施您的相等運算符。它應該是:

def == other 
    other_name = case other 
    when Role then other.name 
    when String, Symbol then other.to_s 
    end 
    name == other_name 
end 
+0

這只是一個錯誤(相應更新)的錯字。正如我所說的,檢查平等通常是有效的,除了'include?',它甚至沒有被使用。 – Conkerchen

+0

我在我的模型中試過你的代碼,糾正了相等運算符幷包含了?工作很好... –

+0

我剛開始一個新項目,只是爲了仔細檢查。但它仍然不適用於我。我更新到最新的鋼軌版本3.2.12,仍然是一樣的。很奇怪......你確定,你在has_many關係內嘗試過它,而不是在任意數組上?例如'[Role.create(name:'test'),Role.create(name:'test_2')]。include? 'test'將按預期工作,但是'user.roles.include? 'test''不會。 – Conkerchen