How do I print out the contents of an object in Rails for easy debugging?

前端 未结 8 1139
感情败类
感情败类 2020-12-04 18:32

I think I\'m trying to get the PHP equivalent of print_r() (print human-readable); at present the raw output is:

ActiveRecord::Relation:0x10355d         


        
相关标签:
8条回答
  • 2020-12-04 19:20

    .inspect is what you're looking for, it's way easier IMO than .to_yaml!

    user = User.new
    user.name = "will"
    user.email = "will@example.com"
    
    user.inspect
    #<name: "will", email: "will@example.com">
    
    0 讨论(0)
  • 2020-12-04 19:24

    inspect is great but sometimes not good enough. E.g. BigDecimal prints like this: #<BigDecimal:7ff49f5478b0,'0.1E2',9(18)>.

    To have full control over what's printed you could redefine to_s or inspect methods. Or create your own one to not confuse future devs too much.

      class Something < ApplicationRecord
    
        def to_s
          attributes.map{ |k, v| { k => v.to_s } }.inject(:merge)
        end
    
      end
    

    This will apply a method (i.e. to_s) to all attributes. This example will get rid of the ugly BigDecimals.

    You can also redefine a handful of attributes only:

      def to_s
        attributes.merge({ my_attribute: my_attribute.to_s })
      end
    

    You can also create a mix of the two or somehow add associations.

    0 讨论(0)
提交回复
热议问题