开发者

In Rails, how to handle multiple checked checkboxes, just split on the , or?

Curious what the 'rails way' of handling the situation when a user checks multiple checkboxes (with the same name value), and it gets p开发者_运维知识库osted back to the controller.

How would you check if multiple items were selected, then splitted on the ID values etc.


The easiest way of doing this is to set those checkboxes up to become an array.

HTML:

<input type="checkbox" name="tag_ids[]" value="1" />
<input type="checkbox" name="tag_ids[]" value="2" />
<input type="checkbox" name="tag_ids[]" value="3" />

Controller:

tag_ids = params[:tag_ids]

(Of course, you'd probably be using form_for-based helpers in the view, and therefore mass-assigning the tag IDs. This is just the most generic example.)


f.check_box :tag_ids, {multiple: true}, 1, nil

Is the right answer:

Here is the reason, there is a 'multiple: true' option that allows your input to be placed in an array. If there isn't a multiple: true option this will not be allowed.


Here is an example of view and controller for example where multiple cleaners can be in multiple cities.

<%= form_for(@cleaner) do |f| %>
  <p>
    <%= f.label :cities %><br />
    <% for city in City.all %>
      <%= check_box_tag "cleaner[city_ids][]", city.id, @cleaner.cities.include?(city) %>
      <%=h city.name %><br />
    <% end %>
  </p>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

And in controller

def cleaner_params
  params.require(:cleaner).permit(city_ids: [])
end

You can find complete tutorial on "rails way" of doing this https://kolosek.com/rails-join-table/


In addition to Chuck Callebs answer: When sending an empty string instead of nil or false as unchecked value, Rails will understand to remove associated ids on an update action:

<%= f.check_box :tag_ids, {multiple: true}, tag.id, '' %>


If you want to use a checked param you have to write this :

check_box_tag "tag_ids[]", 1, true

And not this :

check_box_tag 'tag_ids[]', 1, true

It took me a while to figure out, I hope it will help someone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜