how to save array to database in rails

30,999

Solution 1

ActiveRecord::Base.serialize.

For example:

class User < ActiveRecord::Base
  serialize :scholarship
end

user = User.create(:scholarship=> { "name" => "test", "state_ids" => ["1", "2"]})
User.find(user.id).scholarship# => { "name" => "test", "state_ids" => ["1", "2"] }

Solution 2

Also you can use PostrgreSQL support for array storing. (If you're using PG of course). Your migration will look like that:

add_column :table_name, :column_name, :string, array: true, default: []

But don't forget about validations.

Solution 3

In your model have

serialize :state_ids

Here is a link to the documentation

That being said it looks like you're trying to pass state_ids parameters and save it in state_id, is this what you're intending to do?

Share:
30,999

Related videos on Youtube

tardjo
Author by

tardjo

ngomong opo? pokoe joged... nyahaha xD

Updated on June 18, 2020

Comments

  • tardjo
    tardjo about 4 years

    if i have params like this :

    params["scholarship"] = {"name"=>"test", "state_ids"=>["1", "2", "3", "4"]}
    

    and when i create object to database field state_id not save to database?

    how to save to database with format :

    #<Scholarship id: 1, name: "test", state_id: "["1", "2", "3", "4"]">
    

    how do that?

    thanks before

  • Stefan
    Stefan about 10 years
    You should use the plural form for arrays: state_ids
  • Charles Skariah
    Charles Skariah over 7 years
    This is already corrected there.You should have responded there in the comment.Stick with the question