Help us understand the problem. What is going on with this article?

form_forで複数のcheck_boxを表示して配列で取得する方法

More than 3 years have passed since last update.

チェックボックスで複数選択して、その情報を配列で取得する方法。方法は複数あるが今回は、form_forのcheck_boxを例として記載します。

view例

check_boxのオプションにmultipleを使用することによって、:hoge_idsの結果を配列で渡せれる。

= form_for @form_hoge, url: { action: 'update' } do |f|
  div
    - @hoges.each do |hoge|
      div
        label
          = f.check_box :hoge_ids, { multiple: true, checked: hoge[:checked], disabled: hoge[:disabled] }, hoge[:id]
          = hoge[:name]
  • 自動的にhiddenが作成されて、0の値が含まれる配列になる。チェックした値のみの配列を取得したい場合は、オプションで下記設定する。
include_hidden: false

= f.check_box :hoge_ids, { multiple: true, checked: hoge[:checked], disabled: hoge[:disabled], include_hidden: false }, hoge[:id]

controller例

  def show
    @hoge = Hoge.new
  end

  def update
    @hoge = Hoge.new(hoge_params)
  end

  private

  def hoge_params
    params.require(:hoge).permit(hoge_ids: [])
  end

取得結果

"hoge_ids" => ["0", "1", "0","0","3"]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした