Rails 3 - How to Create a JSON Object to store in the database
Current versions of rails support json serialisation out of the box. Define your field as a string (or text) in the migration and then:
class Foo < ActiveRecord::Base serialize :field, JSONendbar = Foo.newbar.field = [1,2,3]bar.save
First, definitely check out ActiveRecord serialize and see if it does what you need: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize
However, if you need JSON specifically (serialize uses YAML by default), then you can always fake it by hand.
You can simply build a hash in Ruby and then call to_json
on it before assigning it to your model attribute.
data = { 'photoid' => 123, 'photoname' => "asdasd", 'creator_id' => "asdasd" }myrecord.stored_data = data.to_jsonmyrecord.save
Take a look at this: http://github.com/laserlemon/vestal_versions
If it's not what you're looking for, it will at least show you it's done.