LoginSignup
46
44

More than 5 years have passed since last update.

【Rails4】複数選択チェックボックス(check_box_tag)

Last updated at Posted at 2014-05-25

check_boxは真偽値のカラム用になっているため、check_box_tagを使います。

check_box_tag(name, value = "1", checked = false, options = {})

配列で受け取るためのモデル名つきname属性を指定します
hidden要素は全てチェックなしでの更新をするために必要です

<%= form_for @user do |f| %>
  <%= hidden_field_tag 'image[id][]' %>
  <% @image.each do |i| %>
    <%= check_box_tag 'image[id][]', i.id, checked = false, :id => "image_#{i.id}" %>
  <% end %>
<% end %>

checkedの判定を反映させたい場合は、以下のようにやるといいらしいです

<%= check_box_tag 'image[id][]', i.id, @user.images.include?(i.id), :id => "image_#{i.id}" %>
46
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
44