58
55

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.

railsで複数チェックボックスの値を使って検索する

Last updated at Posted at 2014-05-11

Rails 4.0.3です。
railsで複数チェックボックスの値を使ってテーブルの検索するには、check_boxタグのmultipleオプションを利用します。

例)性別判定
gender.html.haml

= form_for @search_form, url: hoge_path, remote: true, html: {method: :get} do |f|
  %table
    %tr
      %th 性別 :
      %td
        = f.check_box :gender, {multiple: true}, 'male',nil
        男性
        = f.check_box :gender, {multiple: true}, 'female',nil
        女性
        = f.check_box :gender, {multiple: true},'empty',nil
        データなし 

実行結果

<input id="search_form_gender_male" name="search_form[gender][]" type="checkbox" value="male" />
男性
<input id="search_form_gender_female" name="search_form[gender][]" type="checkbox" value="female" />
女性
<input id="search_form_gender_empty" name="search_form[gender][]" type="checkbox" value="empty" />
データなし
  • multipleオプションはrails doc http://railsdoc.com/references/check_boxには載ってませんが、使えます。

  • multipleオプションを使うことで、genderの結果が配列で渡されます。

  • 男性、女性にチェックを入れた場合以下のように値が取れます。
    "search_form"=>{"gender"=>["male", "female"]}

  • 最後のnilはhidden 0をなくすためのものです。

  • この値をコントローラー経由でモデル側でscopeで受け取って処理します
    gender_controller.rb

(中略)
@search_form =  SearchForm.new params[:search_form]
@results = Gender.search(:gender =>@search_form.gender)

Gender.rb

(中略)
scope :by_gender, lambda {|gender| where(gender: gender)}
def self.search(params={})
    profile_result = profile_result.by_gender(params[:gender])
    return profile_result
end

参考:
http://apidock.com/rails/ActionView/Helpers/FormHelper/check_box

58
55
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
58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?