Multiple select issue with a HABTM relationship using Rails 4
Asked Answered
S

2

24

Although the code seems to be right, when I try to send the form, the values of the multiple select aren't being sent.

If I just remove the multiple option, everything works as expected considering just one value, but it's important to store more than one tag per transaction.

Model

Transaction.rb

class Transaction < ActiveRecord::Base
    has_and_belongs_to_many :tags

Tag.rb

class tag < ActiveRecord::Base
    has_and_belongs_to_many :transactions

View

<%= form.collection_select :tag_ids, @tags, :id, :name, {}, 
    {:multiple => true} %>

Result:

<select id="transaction_tag_ids" multiple="multiple" name="transaction[tag_ids][]">  
    <option value="1">..</option>
</select>
Shot answered 18/7, 2013 at 21:25 Comment(0)
S
44

Be sure what you properly allow received params for mass assignment.

You said that the one param works, so I assume what you have somewhere in your controller something like:

params.require(:transaction).permit(:name, :tag_ids)

So you need allow to receive an array:

params.require(:transaction).permit(:name, :tag_ids => [])
Salomon answered 30/7, 2013 at 14:27 Comment(0)
K
0

I solved my problem using

{:health_unit_ids => []}

Rails 4 no accepted without {}

Kalgoorlie answered 18/4, 2016 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.