how would I do such a thing? I want to be able to store the params object into a string attribute of a model, and be able to deserialize it into params hash object again, how would I do this in ruby? or is there an out of the box solution in rails?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method serialize. This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work.
class User < ActiveRecord::Base
serialize :preferences
end
user = User.create(preferences: {background: "black", display: "large"})
User.find(user.id).preferences
# => {background: "black", display: "large"}
回答2:
Mori's answer is correct, but if your data type in the model is truly a string, it may not fit. Suggest you use text instead.