Iterating over an ActiveRecord object's properties
I'm trying to iterate over the properties of an ActiveRecord object. I've been searching online but I keep coming up blank. I thought I was getting warm with object.to_enum, but despite the fact that this returns an Enumerator object, I still get the error saying that 'each' is undefined for my object.
Calling object.methods gives me a bunch of inherited stuff I 开发者_如何学Cdon't want. Calling object.instance_variables doesn't give me anything close to what I seek. I'm guessing this isn't hard, but I just haven't figured it out yet :) Can anyone help? Thanks!
Have you tried object.attributes
? This will give you a hash of all the attributes on the object mapping the attribute name to the attribute value.
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-attributes ActiveRecord::Base#attributes is the method to do want
精彩评论