how to save array to database in rails
30,999
Solution 1
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?
Related videos on Youtube
![tardjo](https://i.stack.imgur.com/tdk3V.jpg?s=256&g=1)
Comments
-
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 about 10 yearsYou should use the plural form for arrays:
state_ids
-
Charles Skariah over 7 yearsThis is already corrected there.You should have responded there in the comment.Stick with the question