为什么不直接转换成数组呢?
ap Post.all.to_a
或者你可以创建一个补丁:
alias :old_ap :ap
def ap(object, option={})
if object.class == ActiveRecord::Relation::ActiveRecord_Relation_Post
old_ap object.to_a, option
else
old_ap object, option
end
end
你是对的。也许这是与 Rails4 不兼容的问题,因为 github 上的最后一次提交是 6 个月前。问题来了:
awesome_print-1.2.0/lib/awesome_print/ext/active_record.rb@24
def cast_with_active_record(object, type)
cast = cast_without_active_record(object, type)
return cast if !defined?(::ActiveRecord)
if object.is_a?(::ActiveRecord::Base)
cast = :active_record_instance
elsif object.is_a?(Class) && object.ancestors.include?(::ActiveRecord::Base)
cast = :active_record_class
elsif type == :activerecord_relation #HERE the problem
cast = :array
end
cast
end
当type 为:activerecord_relation 时,该方法将强制转换为数组
在 awesome_print-1.2.0/lib/awesome_print/inspector.rb@151
def printable(object)
case object
when Array then :array
when Hash then :hash
when File then :file
when Dir then :dir
when Struct then :struct
else object.class.to_s.gsub(/:+/, "_").downcase.to_sym #HERE gets the type
end
end
但是rails4中Relation对象的类是这样的:
> Post.all.class
=> ActiveRecord::Relation::ActiveRecord_Relation_Post
所以cast_with_active_record 中的条件获得类型“activerecord_relation_activerecord_relation_post”而不是“activerecord_relation”。然后条件失败,并且没有进行强制转换。
这是一个可能有效的新补丁:
module AwesomePrint
class Inspector
alias_method :old_printable, :printable
private
def printable(object)
if object.class.to_s.downcase.include?("activerecord_relation")
return :activerecord_relation
end
old_printable(object)
end
end
end