如何在Rails中打印对象的内容以便于debugging?
我想我试图得到相当于print_r()的PHP(打印人类可读的); 目前原始产量是: 
 ActiveRecord::Relation:0x10355d1c0 
我该怎么办?
 我通常首先尝试。 .inspect ,如果这不给我我想要的,我会切换到.to_yaml 。 
 class User attr_accessor :name, :age end user = User.new user.name = "John Smith" user.age = 30 puts user.inspect #=> #<User:0x423270c @name="John Smith", @age=30> puts user.to_yaml #=> --- !ruby/object:User #=> age: 30 #=> name: John Smith 
希望有所帮助。
在你的模型中定义to_s方法。 例如
 class Person < ActiveRecord::Base def to_s "Name:#{self.name} Age:#{self.age} Weight: #{self.weight}" end end 
然后当你用#puts打印它时,它会显示那些variables的string。
在Rails中,您可以使用debugging“Helper ActionView :: Helpers :: DebugHelper ”在“视图”中打印结果
 #app/view/controllers/post_controller.rb def index @posts = Post.all end #app/view/posts/index.html.erb <%= debug(@posts) %> #start your server rails -s 
结果(在浏览器中)
 - !ruby/object:Post raw_attributes: id: 2 title: My Second Post body: Welcome! This is another example post published_at: '2015-10-19 23:00:43.469520' created_at: '2015-10-20 00:00:43.470739' updated_at: '2015-10-20 00:00:43.470739' attributes: !ruby/object:ActiveRecord::AttributeSet attributes: !ruby/object:ActiveRecord::LazyAttributeHash types: &5 id: &2 !ruby/object:ActiveRecord::Type::Integer precision: scale: limit: range: !ruby/range begin: -2147483648 end: 2147483648 excl: true title: &3 !ruby/object:ActiveRecord::Type::String precision: scale: limit: body: &4 !ruby/object:ActiveRecord::Type::Text precision: scale: limit: published_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter subtype: &1 !ruby/object:ActiveRecord::Type::DateTime precision: scale: limit: created_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter subtype: *1 updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter subtype: *1 
 你需要使用debug(@var) 。 这完全像“print_r”。 
- Xcode – configure:error:在$ PATH中找不到可接受的C编译器
- 从Authlogic迁移到devise
- 检查一个variables是否是Ruby中的一个string
- 如何testing(ActiveRecord)对象相等
- Rails ExecJS :: ProgramError在Pages#home?
- 将数据从SQL Server Express导出为CSV(需要引用和转义)
- NameError(未初始化的常量Paperclip :: Storage :: S3 :: AWS):
- Ruby数组:select(),collect()和map()
- 我如何使用Active Support核心扩展?