how to save array to database in rails

前端 未结 4 844
我在风中等你
我在风中等你 2020-12-10 01:07

if i have params like this :

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

and when i c

相关标签:
4条回答
  • 2020-12-10 01:15

    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?

    0 讨论(0)
  • 2020-12-10 01:26
    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.

    0 讨论(0)
  • 2020-12-10 01:27

    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"] }
    
    0 讨论(0)
  • 2020-12-10 01:38

    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.

    0 讨论(0)
提交回复
热议问题