LoginSignup
4
3

More than 3 years have passed since last update.

collection_check_boxesで 'id' と 'for' 属性 をカスタマイズする(simple form)

Last updated at Posted at 2020-06-19

新規作成(New)と編集(edit)で同じチェックボックスを2つ用意する必要があるのだが、
2つとも同じページに存在するためidがダブってしまい、後から生成される編集(edit)のチェックボックスがうまく選択できない問題が発生。

よって、それぞれ固有のidになるようにカスタマイズする必要がある。
以下がコードです。(simple_form使用)

カスタマイズ無し
<%= f.collection_check_boxes(:status_ids, current_user.statuses, :id, :name, ) do |b| %>
  <%= b.check_box %>
  <%= b.label {b.object.name} %>
<% end %> 
カスタマイズ有り
<%= f.collection_check_boxes(:status_ids, current_user.statuses, :id, :name ) do |b| %>
  <%= b.check_box(:id => "edit_object_ids_#{b.object.id}") %>
  <%= b.label(:for => "edit_object_ids_#{b.object.id}") %>
<% end %> 

参考
https://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes

4
3
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
4
3