D
D
DeepHill2014-06-09 13:31:46
Ruby on Rails
DeepHill, 2014-06-09 13:31:46

Why does FormOptionsHelper collection_check_boxes (Rails 4.1.0) create an empty value (value="")?

There are two models Article and Tag associated with HABTM:
article.rb

class Article < ActiveRecord::Base
  has_and_belongs_to_many :tags
end

tag.rb
class Tag < ActiveRecord::Base
  has_and_belongs_to_many :articles
end

I want to display tags as checkboxes in the article editing form:
_form.html.erb
<p>
    <%= f.label "Tags" %><br>
    <%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name%>
  <p>

generated code like this:
html
<p>
    <label for="article_Tags">Tags</label><br>
    <input checked="checked" id="article_tag_ids_1" name="article[tag_ids][]" value="1" type="checkbox"><label for="article_tag_ids_1">Linux</label><input checked="checked" id="article_tag_ids_3" name="article[tag_ids][]" value="3" type="checkbox"><label for="article_tag_ids_3">Ubuntu</label><input checked="checked" id="article_tag_ids_4" name="article[tag_ids][]" value="4" type="checkbox"><label for="article_tag_ids_4">Windows</label><input name="article[tag_ids][]" value="" type="hidden">
  </p>

accordingly, an empty value is passed to params:
Parameters:
"tag_ids"=>["3",
 ""]

UPD:
Thanks for the answer Dimitriy :
An empty value is used to not write processing for deleting related elements if you do not select more than one checkbox.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
DeepHill, 2014-06-09
@DeepHill

The problem is in this line

<input name="article[tag_ids][]" value="" type="hidden">
generated by collection_check_boxes
Thanks for answering @Vakiliy : An
empty value is used to avoid writing handling for deleting related items unless more than one checkbox is selected.

D
Dimitriy, 2014-06-09
@Vakiliy

I suspect that, in the controller, there is not enough parameter for the white list - tag_ids: []
params.require(:article).permit(...., tag_ids: [])

S
Sergey Toy, 2014-06-09
@Toy

railscasts.com/episodes/196-nested-model-form-part-1 (outdated screencast, but gives an idea of ​​the problem).
And the solution is here: api.rubyonrails.org/classes/ActiveRecord/NestedAtt...

S
shilovk, 2020-04-28
@shilovk

It is necessary to set include_hidden: falseand then the hidden element will not be added to the form.

<%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name, include_hidden: false %>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question