LoginSignup
5
4

More than 5 years have passed since last update.

Rails4 checkboxで複数のチェックを配列で受け取る

Last updated at Posted at 2015-02-15

Rails4使ってて、checkboxで複数のチェックをArrayで受け取る方法

HTML側 (1行目と5行目は関係ない)

<input type="number" name="num">個数
<input type="checkbox" name="gadgets[]" value="iPhone">アイフォン
<input type="checkbox" name="gadgets[]" value="Android">アンドロイド
<input type="checkbox" name="gadgets[]" value="WindowsPhone">ウィンドウズフォン
<input type="text" name="hoge">ほげ

Controller側

gadget_params = params.permit(:num, {:gadgets => []}, :hoge)

これでgadget_paramsは{"name"=>"2", "gadgets"=>["iPhone", "Android"], "hoge"=>"fuga"}みたいになる。

ポイントは
1. HTML側でチェックボックスのnameに[]をつける。こうするとRailsが配列として扱ってくれる
2. StrongParametersのpermitで配列であることを明示する。

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