Skip to content

Instantly share code, notes, and snippets.

@fokayx
Created April 2, 2015 07:22
Show Gist options
  • Save fokayx/58fedfbdecc54306dee0 to your computer and use it in GitHub Desktop.
Save fokayx/58fedfbdecc54306dee0 to your computer and use it in GitHub Desktop.
Serialize ruby on rails

Serialize http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html

# Serialize a preferences attribute.
class User < ActiveRecord::Base
  serialize :preferences
end

# Serialize preferences using JSON as coder.
class User < ActiveRecord::Base
  serialize :preferences, JSON
end

# Serialize preferences as Hash using YAML coder.
class User < ActiveRecord::Base
  serialize :preferences, Hash
end

指定欄位做serialize後,可存入欄位資料類型EX: Hash, Array

class Cagegory < ActiveRecord::Base
  serialize :item, Array
end

就能在Category中的 item 欄位存入 Array,

a = Category.new
a.item = ["1", "2", "3", "4"]
a.save
a => item ["1", "2", "3", "4"]
a.name[1] = "2"
b = ["#{a.name[1]", "#{a.name[3]}"]
b = ["2", "4"]
b.each do |c|
  puts c
end
2
4

嗯...所以要怎麼運用呢 XD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment