更新:
确切的实现方式取决于您的数据库,但是PostgreSQL现在有json
和jsonb
列,可以本地存储哈希/对象数据,并允许您通过ActiveRecord 查询JSON!
更改您的迁移,完成。
class Migration0001
def change
add_column :users, :location_data, :json, default: {}
end
end
原文:
更多细节请参考:rails文档 && apidock
确保你的列是:text
而不是:string
迁移:
$ rails g migration add_location_data_to_users location_data:text
应该会创建:
class Migration0001
def change
add_column :users, :location_data, :text
end
end
你的类会像这样:
class User < ActiveRecord::Base
serialize :location_data
end
可用的操作:
b = User.new
b.location_data = [1,2,{foot: 3, bart: "noodles"}]
b.save
更棒了?!
利用PostgreSQL Hstore。
class AddHstore < ActiveRecord::Migration
def up
enable_extension :hstore
end
def down
disable_extension :hstore
end
end
class Migration0001
def change
add_column :users, :location_data, :hstore
end
end
使用 hstore,您可以在序列化字段上设置属性
class User < ActiveRecord::Base
store_accessor :location_data, :city, :state
end