gpt4 book ai didi

ruby-on-rails - 在ActiveRecord子类中覆盖 '=='方法有意义吗?

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:48 24 4
gpt4 key购买 nike

Rails 的 ActiveRecord::Base 类定义了一个 ==如果对象相同或它们具有相同的 ID,则返回 true 的方法。

我已经在我的几个 Rails 模型中覆盖了 == 以允许更有意义的相等条件。当我直接比较对象时(例如,通过 script/console),这些工作正常,但是如果我做类似 my_array_of_models.include? other_modelinclude? 总是返回 false。即使数组包含一个“相等”的对象(根据我的定义)。

我已经解决了这个问题,例如,my_array_of_models.any? { |el| el.attr == other_model.attr }(无论如何,我认为这是鼓励您进行比较的方式),但我想知道:覆盖 == 是否有意义> 在 ActiveRecord 模型中,或者 ActiveRecord 是否在高层做了一些事情使得这种被覆盖的方法变得无用(或者更糟,危险)?

来源

下面是我重写方法的实现。有两个类,UserContact用户 具有唯一的电子邮件地址,因此如果电子邮件地址相同,则 == 返回 true。 ContactUsers 之间的桥梁(就像社交网络中的“ friend ”关系),如果他们有相同的 应该返回 true >user_id.

class User < ActiveRecord::Base
def ==(other)
other.respond_to?(:email) and self.email == other.email
end
end

class Contact < ActiveRecord::Base
def ==(other)
if other.class == self.class
self.user == other.user
elsif other.kind_of? User
self.user == other
else
false
end
end
end

正如我所指出的,它在直接比较时有效(例如,one_object == another_object),但是 my_array_of_objs.include? included_obj 始终返回 false

最佳答案

也许阅读这篇文档对您有启发:

http://ruby-doc.org/core/classes/Object.html#M000341

array_of_models.include?(my_object) 可能不起作用,因为 == 未用于测试集合是否具有对象。它使用 equal?

编辑

OP 断言即使他重写了他的模型的 == 方法,array.include?(obj) 也返回 false 是不正确的。让我们看看这个:

class Event < ActiveRecord::Base
def ==(that)
if(that.eventname == self.eventname)
true
else
false
end
end
end
>> a << Event.find(1)
=> [#<Event id: 1, eventname: "hemant", foo: nil, created_at: "2009-06-24 21:33:00", updated_at: "2009-06-24 21:33:00">]

>> b = Event.find(2)
=> #<Event id: 2, eventname: "hemant", foo: nil, created_at: "2009-06-24 21:33:04", updated_at: "2009-06-24 21:33:04">

>> a.include?(b)
=> true

显然那不是真的。但无论如何,我认为由于 AR 以特定方式定义了 ==,因此覆盖它不是一个好主意。这可能会导致难以检测错误。

关于ruby-on-rails - 在ActiveRecord子类中覆盖 '=='方法有意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1038539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com