LoginSignup
2
10

More than 5 years have passed since last update.

RubyOnRails 数量変更可能なセレクトボックス

Last updated at Posted at 2017-07-21

今からプールに泳ぎに行くんですが、その前にメモ。

作り方

options_for_selectで簡単に作れます。
こんな感じで書くと最初から選択した状態にしてくれます。
@numbersには任意の配列を入れておきましょう。

=f.select :quantity, options_for_select(@numbers, {selected: cart.quantity.to_i} )

画像

スクリーンショット 2017-07-21 13.31.42.png

完成コード

#carts/show.html.haml
=form_for cart, url:"/update_item/#{cart.item_id}", method: :post do |f|
  =f.select :quantity, options_for_select(@numbers, {selected: cart.quantity.to_i} )
  =f.submit "数量の変更を確定"

Railsガイドによるところ。

options_for_selectでは、デフォルトにしたいオプションを値を渡すことでデフォルト値を設定できます。
生成されるオプション内部の値がこの値とマッチすると、Railsはselected属性を自動的にそのオプションに追加します。

ちょっと良くわかりませんでしたが、とにかくできたので良いとします。
以上です。

参考サイト:

Action View フォームヘルパー

2
10
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
2
10