0

I am needing to have an attribute in my form (:supported_media_types) accept an array of values.

For example, I want the user to be able to click on both JPG and PNG if required.

I have setup a select2 drop down with multiple: true

Is there an easy way to achieve this or am I required to create a join table?

<%= f.select :supported_ad_types, supported_types_of_media, {include_blank: true}, {class: 'filter_select', name: 's2id_location_supported_ad_types[]', style:'width:100%;', placeholder: 'Supported File Types', required: true, multiple: true} %>
RubyNewbie
  • 547
  • 5
  • 21

2 Answers2

2

use select_tag 'supported_ad_types[]' ... to get array params.

In your model use serializer :supported_ad_types, array to save array params.

jan
  • 93
  • 4
0

Create a serialized attribute like this:

1 - Add a column to your migration normally, as text:

rails g model Image types:text
rake db:migrate

2 - In your class:

class Image < ActiveRecord::Base
    serialize :types, Array
end

Now, you can do things like:

i = Image.new
i.types << "png"
i.types << "jpg"
i.save
=> #<Image id: 1, types: ["png", "jpg"], created_at: "2014-08-11 22:44:08", updated_at: "2014-08-11 22:44:08">
Tiago Farias
  • 3,397
  • 1
  • 27
  • 30
  • Thanks! Seems to be passing in a blank value on first record. I changed my (include_blank: false) – RubyNewbie Aug 11 '14 at 23:07
  • "supported_ad_types"=>["", "JPG", "BMP"], – RubyNewbie Aug 11 '14 at 23:08
  • That's something to do with the select. – Tiago Farias Aug 11 '14 at 23:09
  • As for the blank value being persisted, take a look at this (there is also a workaround): http://stackoverflow.com/questions/8929230/why-is-the-first-element-always-blank-in-my-rails-multi-select-using-an-embedde . And consider accepting the answer if it helped. – Tiago Farias Aug 11 '14 at 23:14
  • Accepted answer along with Jan. – RubyNewbie Aug 11 '14 at 23:27
  • Is there a way to now be able to display this data? On my 'show' view, all I see are brackets []. But I am able to see in my logs that the data array is saving – RubyNewbie Aug 11 '14 at 23:28
  • What do you mean? To just exhibit like: PNG, BMP ? – Tiago Farias Aug 11 '14 at 23:38
  • What I realized looking at the logs was that the data was being 'submitted' correctly, but not saving. Inside my console I can see: supported_ad_types: [], Trying to figure out why the data is not passing through. I am using Rails 4 – RubyNewbie Aug 11 '14 at 23:43