给定一个来自 ActiveRecord
的命名 Foo
的集合,为什么 Array#include?
似乎没有调用 Foo.= =
但是 index
呢?
class Foo < ActiveRecord::Base
def ==(s)
self.name == s
end
end
class Bar < ActiveRecord::Base
has_many :foos
end
bar.foos << Foo.new( :name => 'hmm' )
bar.foos.all.include?('hmm') # does select all from db every time
=> true
bar.foos.include?('hmm') # does not go to db, but does not find the Foo!
=> false
bar.foos.index('hmm') # does not go to db, but does find the Foo[0] !
=> 0
bar.foos.index('eh') # no such object
=> nil
我对代理的了解很浅,但是(没有绕过 AR 源代码)为什么索引看似正确但包含?不是!?
这是代理行为中的错误吗,和/或是否在某处记录了此行为?
谢谢。
最佳答案
这是因为 bar.foos
不返回一个 ActiveRecord::Base
对象,而是返回一个 AssociationProxy
(参见 association_proxy .rb
).
我不建议您在关联代理中重新定义 ==
,否则您将更改应用程序中所有关联的行为。
关于ruby-on-rails - 阵列::包括?在 ActiveRecord 集合上不调用 op==?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2430370/