dziorkowsky
dziorkowsky

Reputation: 51

How save multiselect values to database

How can I add values to string field in database from multiple select.

I have field in database:

t.string   "types"

and view:

<%= f.select :order, [["One", 1], ["Two", 2], ["Three", 3]], {}, { :class => 'form-control', :multiple => true } %>

Maybe serialize or json is goot idea? Is it possible save and simple way read this?

Upvotes: 0

Views: 1894

Answers (2)

Milind
Milind

Reputation: 5112

You can pass a class to serialize:

  class User < ActiveRecord::Base
      serialize :order, Array
    end
    The above ensures that order as an Array:

    User.new
    #=> #<User id: nil, order: [], created_at: nil, updated_at: nil>
    Note that you might have to convert existing fields if the types don't match.

Upvotes: 1

RichardAE
RichardAE

Reputation: 2970

You can use rails serialize on the column:

serialize :order, Hash

Or for JSON (depending what you want to do with it):

serialize :order, JSON

However, the columns needs to be of type 'text' not 'string' for serialize to work, so be sure to create a migration to change the column type.

rails g migration change_order_type_in_table_name

class ChangeOrderTypeInTableName < ActiveRecord::Migration
  def up
    change_column :my_table, :order, :text
  end

  def down
    change_column :my_table, :order, :string
  end
end

Upvotes: 1

Related Questions