Last active
January 20, 2016 11:14
-
-
Save jeanbaptistebeck/8dbc2ec6c542d474fc8b to your computer and use it in GitHub Desktop.
Serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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