【问题标题】:Rails console compare model instancesRails 控制台比较模型实例
【发布时间】:2013-06-11 12:24:08
【问题描述】:

有没有办法比较模型的两个实例,比如

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

【问题讨论】:

    标签: ruby-on-rails ruby rails-console


    【解决方案1】:

    不使用库或定义自定义方法,您可以轻松获得两个模型之间的差异。

    例如,

    a = Foo.first
    b = Foo.second
    
    a.attributes = b.attributes
    
    a.changes #=> {"id" => [1,2] }
    

    【讨论】:

      【解决方案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
      

      【讨论】:

        【解决方案3】:

        如果您想要所有不同字段及其值的映射,您可以使用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']}
        

        【讨论】:

          猜你喜欢
          • 2013-03-22
          • 1970-01-01
          • 1970-01-01
          • 2022-08-15
          • 2011-01-31
          • 2015-11-07
          • 2010-11-18
          • 2016-03-05
          • 2019-05-10
          相关资源
          最近更新 更多