LoginSignup
13
10

More than 5 years have passed since last update.

collection_check_boxesのブロック内で任意の属性の値を使用する

Posted at

投稿にカテゴリーを設定できるようにするような時、collection_check_boxesは非常に役に立つヘルパーですが、如何せん情報が少ないもので……。

このヘルパーメソッドの基本的な使い方は以下のような感じです。まあ何てことはない。

<%= f.collection_check_boxes :category_ids, Category.all, :id, :name do |b| %>
  <% b.label { b.check_box + b.text } %>
<% end %>

このヘルパーメソッドに渡すブロックの中で適当な属性の値を取得したい時は b.object プロパティを経由して直接レコードにアクセスすることが可能です。

<%= f.collection_check_boxes :category_ids, Category.all, :id, :name do |b| %>
  <% b.label(data-color: b.object.color) { b.check_box + b.text } %>
<% end %>
13
10
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
13
10