LoginSignup
3
2

More than 5 years have passed since last update.

grouped_options_for_select で optgroup 要素に任意の属性を設定したい

Posted at

grouped_options_for_select なんてあまり使われてなさそうなのでニッチなネタですが、備忘録がてら投稿します。

grouped_options_for_select を使う際に optgroup 要素にも任意の data 属性を設定したいと思いました。しかし、リファレンスを見てもその方法は載ってない…。
仕方がないので ソース を読んでみました。

# grouped_options_for_select メソッドの一部
grouped_options.each do |container|
  html_attributes = option_html_attributes(container)

  if divider
    label = divider
  else
    label, container = container
  end

  html_attributes = { label: label }.merge!(html_attributes)
  body.safe_concat content_tag(:optgroup, options_for_select(container, selected_key), html_attributes)
end

すると optgroup タグを生成する際に html_attributes というローカル変数でオプションを渡しているみたいです。
そして html_attributes を作っている option_html_attributes の実装は以下のようになっています。

def option_html_attributes(element)
  if Array === element
    element.select { |e| Hash === e }.reduce({}, :merge!)
  else
    {}
  end
end

どうやら配列にハッシュを含めれば、そのハッシュの部分が content_tag のオプションに渡されそうですね。

grouped_options = [
  ['1 年生', [['nori', '乃莉'], ['nazuna', 'なずな']], { data: { grade: 1 }, class: 'hidamari' }],
  ['2 年生', [['yuno', 'ゆの'], ['miyako', '宮子']], { data: { grade: 2 }, class: 'hidamari' }],
  ['3 年生', [['sae', '沙英'], ['hiro', 'ヒロ']], { data: { grade: 3 }, class: 'hidamari' }]
]

# Rails コンソールで試したので、helper 経由で呼び出しています。
helper.grouped_options_for_select(grouped_options)
<optgroup label="1 年生" data-grade="1" class="hidamari">
  <option value="nori">乃莉</option>
  <option value="nazuna">なずな</option>
</optgroup>
<optgroup label="2 年生" data-grade="2" class="hidamari">
  <option value="yuno">ゆの</option>
  <option value="miyako">宮子</option>
</optgroup>
<optgroup label="3 年生" data-grade="3" class="hidamari">
  <option value="sae">沙英</option>
  <option value="hiro">ヒロ</option>
</optgroup>

できた :v:

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