Reputation: 8730
In multi selected :selected=>@campaign.categories.pluck(:name)
not working and even not giving any error
<%= f.select(:category, options_for_select(Category.all.map{|u| [u.name, u.id]}, :selected => @campaign.categories.pluck(:name) ), {}, {:multiple => true,:required => true, :class => 'form-control' }) %>
Upvotes: 0
Views: 54
Reputation: 52357
There are few issues with your code.
Category.all.map{|u| [u.name, u.id]}
is extremely inefficient way of achieving what you need, since loads the whole Category table into memory prior processing. Here, really, you would need to use pluck:
Category.pluck(:name, :id)
Next thing, is that you can not have a collection as a selected value.
You have to actually select a value.
<%= f.select(
:category,
options_for_select(
Category.pluck(:name, :id),
selected: @campaign.categories.pluck(:name).first # concrete value here, not a collection
),
{},
multiple: true,
{:multiple => true,:required => true, :class => 'form-control'}
) %>
Upvotes: 2
Reputation: 12320
You can try below
<%= f.select(:category, options_for_select(Category.all.map{|u| [u.name, u.id]}, @campaign.categories.map{|j| [j.id]} ),:multiple => true, :required => true, :class => 'form-control' ) %>
or
<%= f.select(:category, options_for_select(Category.pluck(:name, :id), @campaign.categories.pluck(:id) ), :multiple => true, :required => true, :class => 'form-control' )
Upvotes: 1