是否有办法比较两个模型实例,如
Model.compare_by_name("model1", "model2")将列出不同的列字段。
您可以使用 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']}
没有标准的比较器。标准的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
不需要使用库或定义一个自定义方法,你可以很容易地得到两个模型之间的差异。
比如说,你可以在两个模型之间很容易地得到差异。
a = Foo.first
b = Foo.second
a.attributes = b.attributes
a.changes #=> {"id" => [1,2] }