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} %>

2 Answers 2

2

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

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

Sign up to request clarification or add additional context in comments.

Comments

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">

8 Comments

Thanks! Seems to be passing in a blank value on first record. I changed my (include_blank: false)
"supported_ad_types"=>["", "JPG", "BMP"],
That's something to do with the select.
As for the blank value being persisted, take a look at this (there is also a workaround): stackoverflow.com/questions/8929230/… . And consider accepting the answer if it helped.
Accepted answer along with Jan.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.