简体   繁体   中英

Ruby: How to write an array to postgresql?

This is the migration file:

class AddDependentColumnToFeatures < ActiveRecord::Migration
  def change
    add_column :features, :dependent, :string, array: true, default: []
  end
end

this is a part of the array - the important field is "dependent":

... display_on_detail_view"=>"1", "description"=>"", "dependent"=>["569", "571"] ...

it is written on a form submit per "update_attributes" (Rails 3.2.13)

My problem now is, that in the database the migrate file created a "string" column with a default length of 255 characters.

the above array then looks like this, after it is put into the pg-database:

---
- !binary |-
  NTY5
- !binary |-
  NTcx

which is not very helpful as this is just a test and the array will get way larger in production mode like 800 numbers instead of 2 - so the column length of 255 characters won't last long - is there a different way to store that array into the database? or am i already doing something wrong?

You should use the column type :text instead of :string in your migration.

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

class Feature < ActiveRecord::Base
  serialize :dependent, Array 
end

Feature.last.dependent #will return you array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM