はじめに
この記事は2021年1月にまとめていた「細かいつまずいたことをメモしておく(1月編)をそれぞれ投稿した内容になります
解決方法が最新でない可能性もありますのでご了承ください
問題
この記事を参考に複数選択可能なチェックボックスを作成した
chackboxでmultiple
をつけると配列で値を受け取れるのだが、params.require
で値を受け取れるとnil
になってしまった
解決方法
以下のようにしたところ解決した
test.html.erb
<div class='d-inline text-nowrap ml-1'>
<label class='fw-normal'>
<%= f.check_box :color, {multiple: true}, '青色', nil %>
青色
</label>
</div>
<div class='d-inline text-nowrap ml-1'>
<label class='fw-normal'>
<%= f.check_box :color, {multiple: true}, '黄色', nil %>
黄色
</label>
</div>
test_controller.rb
def notebook_params
notebook_params = params.require(:notebook).require(:size,
:width)
notebook_params[:color] =
params.require(:notebook).permit({:color => []})[:color]
notebook.rb
serialize :color, Array
before_save do
self.color.split(',').map{ |m| m.delete('[]"\\')} if attribute_present?("color")
end
これで配列にして保存ができるようになった。パラメータの取得が特殊になっている