dheil February 2016

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?

Answers


Kimmo Lehto February 2016

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


Gourav Naik February 2016

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

Post Status

Asked in February 2016
Viewed 1,142 times
Voted 12
Answered 2 times

Search




Leave an answer