Rails控制台比较模型实例

问题描述 投票:2回答:3

是否有办法比较两个模型实例,如

Model.compare_by_name("model1", "model2")将列出不同的列字段。

ruby-on-rails ruby rails-console
3个回答
3
投票

您可以使用 ActiveRecord::Diff 如果你想要一个所有不同字段及其值的映射。

alice = User.create(:name => 'alice', :email_address => '[email protected]')
bob = User.create(:name => 'bob', :email_address => '[email protected]')    
alice.diff?(bob)  # => true
alice.diff(bob)  # => {:name => ['alice', 'bob'], :email_address => ['[email protected]', '[email protected]']}
alice.diff({:name => 'eve'})  # => {:name => ['alice', 'eve']}

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

0
投票

不需要使用库或定义一个自定义方法,你可以很容易地得到两个模型之间的差异。

比如说,你可以在两个模型之间很容易地得到差异。

a = Foo.first
b = Foo.second

a.attributes = b.attributes

a.changes #=> {"id" => [1,2] }
© www.soinside.com 2019 - 2024. All rights reserved.