56
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

チェックボックスで複数選択して、その情報を配列で取得する方法。方法は複数あるが今回は、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"]
56
47
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
56
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?