【发布时间】:2013-06-11 12:24:08
【问题描述】:
有没有办法比较模型的两个实例,比如
Model.compare_by_name("model1", "model2") 将列出不同的列字段
【问题讨论】:
标签: ruby-on-rails ruby rails-console
有没有办法比较模型的两个实例,比如
Model.compare_by_name("model1", "model2") 将列出不同的列字段
【问题讨论】:
标签: ruby-on-rails ruby rails-console
不使用库或定义自定义方法,您可以轻松获得两个模型之间的差异。
例如,
a = Foo.first
b = Foo.second
a.attributes = b.attributes
a.changes #=> {"id" => [1,2] }
【讨论】:
对此没有标准比较器。标准 ActiveModel 比较器:
Returns true if comparison_object is the same exact object, or comparison_object is of the same type and self has an ID and it is equal to comparison_object.id.
您可以使用 activesupport 的 Hash#diff 编写自己的代码。希望像下面这样的内容可以帮助您入门:
def Model.compare_by_name(model1, model2)
find_by_name(model1).attributes.diff(find_by_name(model2).attributes)
end
【讨论】:
如果您想要所有不同字段及其值的映射,您可以使用ActiveRecord::Diff。
alice = User.create(:name => 'alice', :email_address => 'alice@example.org')
bob = User.create(:name => 'bob', :email_address => 'bob@example.org')
alice.diff?(bob) # => true
alice.diff(bob) # => {:name => ['alice', 'bob'], :email_address => ['alice@example.org', 'bob@example.org']}
alice.diff({:name => 'eve'}) # => {:name => ['alice', 'eve']}
【讨论】: