How to Convert an Object into a Hash

J

Jason Vogel

I have an object (happens to be an ActiveRecord Model), but this is
not a Rails question.

params = { :contract_id => contract_payment['contract_id'], :amount =>
contract_payment['amount'] }

params = contract_payment.to_hash # This is what I want to do...

I want to "automagically" convert the contract_payment object to a
hash.

I would really appreciate any help.

Thanks,
Jason
 
E

Ezra Zygmuntowicz

I have an object (happens to be an ActiveRecord Model), but this is
not a Rails question.

params = { :contract_id => contract_payment['contract_id'], :amount =>
contract_payment['amount'] }

params = contract_payment.to_hash # This is what I want to do...

I want to "automagically" convert the contract_payment object to a
hash.

I would really appreciate any help.

Thanks,
Jason


Since you are using ActiveRecord you can already get the attributes
hash:

contract_payment.attributes

Cheers-

-- Ezra Zygmuntowicz
-- Lead Rails Evangelist
-- (e-mail address removed)
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)
 
D

Daniel Finnie

I don't know how the internals of contract_payment's class is set up,
but you could do this in some cases:
daniel@daniel-desktop:~$ irb=> #<Car:0xb7bd566c @color="green", @owner="Me!", @model_year=2007,
@make="Ford">
myCar.instance_variables => ["@color", "@owner", "@model_year", "@make"]
properties = Hash.new => {}
myCar.instance_variables.each {|x| properties[x[1..-1]] =
myCar.instance_variable_get(x) }
=> ["@color", "@owner", "@model_year", "@make"]

Jason said:
I have an object (happens to be an ActiveRecord Model), but this is
not a Rails question.

params = { :contract_id => contract_payment['contract_id'], :amount =>
contract_payment['amount'] }

params = contract_payment.to_hash # This is what I want to do...

I want to "automagically" convert the contract_payment object to a
hash.

I would really appreciate any help.

Thanks,
Jason
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top