在我的一个模型中,我定义了相等也可以使用字符串和符号。角色是等于另一个角色(或字符串或符号),如果它的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