Skip to content

Instantly share code, notes, and snippets.

@jeanbaptistebeck
Last active January 20, 2016 11:14
Show Gist options
  • Save jeanbaptistebeck/8dbc2ec6c542d474fc8b to your computer and use it in GitHub Desktop.
Save jeanbaptistebeck/8dbc2ec6c542d474fc8b to your computer and use it in GitHub Desktop.
Serialization
class User < ActiveRecord::Base
serialize :preferences, Hash
def initialize(preferences = {})
@preferences = preferences
end
end
user = User.create({ food: { tomatoes: true, salad: false }, sleep: { light: false, noise: false } })
puts user.preferences
# { food: { tomatoes: true, salad: false }, sleep: { light: false, noise: false } }
puts user.preferences[:food]
# { food: { tomatoes: true, salad: false } }
puts user.preferences[:food][:salad]
# false
user.preferences[:sleep] = { light: true, noise: false }
user.save
puts user.preferences
# { food: { tomatoes: true, salad: false }, sleep: { light: true, noise: false } }
user.preferences[:drinks] = { tea: true, coffe: false }
user.save
puts user.preferences
# { food: { tomatoes: true, salad: false }, sleep: { light: true, noise: false }, drinks: { tea: true, coffe: false } }
# For further validations
gem 'validates_serialized'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment