在我的一個模型中,我定義了相等也可以使用字符串和符號。角色是等於另一個角色(或字符串或符號),如果它的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_a
或Role
的實際實例嗎?
這是什麼:'User.roles.class'在你的控制檯? –
@grotori:user.roles.class#=>數組 – Conkerchen