LoginSignup
8
4

More than 5 years have passed since last update.

Rails:form_tagを使用したcheck_boxの利用例

Last updated at Posted at 2018-09-16

form_tagを使用したcheck_boxの実装が初めてだったため、初歩的ですが
備忘録を含め記録として残したいと思います。

完成形はこのようなイメージです。

スクリーンショット 2018-09-15 20.05.47.png

View
<%= form_tag(Controllers/action, method: :get ) do %>
   <ul style="list-style:none;">
     <li><%= check_box "EClist", "Amazon", {:checked => "checked"} %>Amazon</li>
     <li><%= check_box "EClist", "Yahoo", {:checked => "checked"} %>Yahoo</li>
     <li><%= check_box "EClist", "Rakuten", {:checked => "checked"} %>楽天</li>
   </ul>
 <%= submit_tag "商品を検索"%>
<% end %>

EClistと、Amazonを使用し2重ハッシュにします。
{:checked => "checked"}とすることで、デフォルトでチェックした状況にすることができます。

Controller
def hoge
    amazon = params[:EClist][:Amazon]
    yahoo = params[:EClist][:Yahoo]
    rakuten = params[:EClist][:Rakuten]
    #選択されていたら1が入ります。
    puts amazon
    if amazon == "1"
    #テェック済みの時の処理。
    end
  end 

取り出すときは、params[:EClist][:Amazon]とすることで未チェックであれば【0】チェック済みであれば【1】を取得できます。

またチェックを外したい場合は

View
<%= form_tag(Controllers/action, method: :get ) do %>
   <ul style="list-style:none;">
     <li><%= check_box "EClist", "Amazon", {} %>Amazon</li>
     <li><%= check_box "EClist", "Yahoo", {} %>Yahoo</li>
     <li><%= check_box "EClist", "Rakuten", {} %>楽天</li>
   </ul>
 <%= submit_tag "商品を検索"%>
<% end %>

上記の通りにしていただければ、チェックを外せます。

ご参考になれば幸いです。

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