Rails can't write to serialized array field in database

时光总嘲笑我的痴心妄想 提交于 2019-12-20 07:14:05

问题


I have the array on my model and set up, and when I go to write the array onto my record it says COMMIT true, yet checking the field on that record immediately after returns an empty array.

Model:

class Feature < ActiveRecord::Base
  serialize :content, Array
  attr_accessible :content
end

Migration:

class AddContentToFeatures < ActiveRecord::Migration
  def change
    add_column :features, :content, :text, array: true, default: []
  end
end

What I tried, along with various symbol and string syntaxes, is this:

> f=Feature.new
> f.content_will_change! #i feel like i shouldn't have to do this
> f.content = ['sadasd','asdasd']
> f.save!
    BEGIN
    COMMIT
=> true
> f.content
=> []

How do I persist the array on the model?


回答1:


If you're using native PostgreSQL arrays (which you are since you have array: true in your migration) then you shouldn't use serialize at all. serialize is used to store YAML in the database:

serialize(attr_name, class_name_or_coder = Object)

If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, then specify the name of that attribute using this method and it will be handled automatically. The serialization is done through YAML. If class_name is specified, the serialized object must be of that class on assignment and retrieval. Otherwise SerializationTypeMismatch will be raised.

So serialize simply stores a YAML-encoded object inside a text column in the database. But PostgreSQL, ActiveRecord in Rails4, and the underlying PostgreSQL driver all understands arrays without all the YAML unpleasantness.

Leave the array: true in your migration, remove the serialize :content, Array from your model, and it should work fine. As an added bonus, you'll be able to use all of PostgreSQL's array operators and functions to query your content, serialize doesn't allow you to do this.




回答2:


The default data structure for Rails' serializer is a Hash which you are not saving into f.content.

To save an Array to the serialized content, try in your Feature Model the following:

serialize :content, Array


来源:https://stackoverflow.com/questions/35443041/rails-cant-write-to-serialized-array-field-in-database

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