Reputation: 1654
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
Upvotes: 34
Views: 35900
Reputation: 6542
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"] }
Upvotes: 26
Reputation: 1307
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.
Upvotes: 43
Reputation: 4877
state_ids != state_id
you've got 2 different names for your attribute, so they don't line up.
then use serialize :state_ids
once you've renamed the column.
However if you're storing a list of state_ids, i'm going to guess you also have a states table, and so should look into using has_and_belongs_to_many association.
Upvotes: 0