Using Rails serialize to save hash to database
The column type is wrong. You should use Text instead of String. Therefore, your migration should be:
def self.up add_column :users, :multi_wrong, :text end
Then Rails will properly convert it into YAML for you (and perform proper serialization). Strings fields are limited in size and will only hold especially-small values.
UPDATED:
Exact implementation will depend on your database, but PostgreSQL now has json
and jsonb
columns which can natively store your hash/object data and allow you to query against the JSON with ActiveRecord!
change your migration and you're done.
class Migration0001 def change add_column :users, :location_data, :json, default: {} endend
ORIGINAL:
For more details: rails docs && apidock
Make sure your column is :text
and not :string
Migration:
$ rails g migration add_location_data_to_users location_data:text
should create:
class Migration0001 def change add_column :users, :location_data, :text endend
Your Class Would Look Like:
class User < ActiveRecord::Base serialize :location_dataend
Available Actions:
b = User.newb.location_data = [1,2,{foot: 3, bart: "noodles"}]b.save
More Awesome?!
utilize postgresql hstore
class AddHstore < ActiveRecord::Migration def up enable_extension :hstore end def down disable_extension :hstore endend class Migration0001 def change add_column :users, :location_data, :hstore endend
With hstore you can set attributes on the serialized field
class User < ActiveRecord::Base # setup hstore store_accessor :location_data, :city, :stateend
Rails 4 has a new feature called Store, so you can easily use it to solve your problem. You can define an accessor for it and it is recommended you declare the database column used for the serialized store as a text, so there's plenty of room. The original example:
class User < ActiveRecord::Base store :settings, accessors: [ :color, :homepage ], coder: JSONendu = User.new(color: 'black', homepage: '37signals.com')u.color # Accessor stored attributeu.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor# There is no difference between strings and symbols for accessing custom attributesu.settings[:country] # => 'Denmark'u.settings['country'] # => 'Denmark'