可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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'