Using Rails serialize to save hash to database

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

I'm try to save a hash mapping ids to a number of attempts in my rails app. My migration to the database to accommodate this new column:

class AddMultiWrongToUser 

In my model I have:

class User 

But when I use the rails console to test this by doing:

user = User.create() user.multi_wrong = {"test"=>"123"} user.save

The output is false. What's going wrong here?

回答1:

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.



回答2:

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   end end

Your Class Would Look Like:

class User 

Available Actions:

b = User.new b.location_data = [1,2,{foot: 3, bart: "noodles"}] b.save

More Awesome?!

utilize postgresql hstore

class AddHstore 

With hstore you can set attributes on the serialized field

class User 


回答3:

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  'Denmark' u.settings['country'] # => 'Denmark'


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!