0
0

More than 1 year has passed since last update.

Railsで複数選択可能なチェックボックスから受け取ったパラメータがnilになる

Posted at

はじめに

この記事は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

これで配列にして保存ができるようになった。パラメータの取得が特殊になっている

0
0
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
0
0