LoginSignup
2
4

More than 5 years have passed since last update.

number_fieldの値をそのまま計算しようとしたら怒られた

Last updated at Posted at 2016-11-12

金額を入力するfieldを作成

***.haml
= form_tag update_path  do
  = label_tag :price
  = number_field_tag :price

  .actions
    = submit_tag 'Save'
    = link_to 'Back', :back

入力された金額を100倍して保存

Controller.rb
  def update
    if params[:price] != nil
      item.price = params[:price] * 100
      item.save
    end
  end

金額を入力してSaveをするとString can't be coerced into BigDecimalと怒られた。

改めてparamsの中を確認して見ると"price"=>"100"となっていた
number_fieldでもparamsで取得したさいには、文字型なんですね。。。

というわけで、コントローラーを修正

Controller.rb
  def update
    if params[:price] != nil
      item.price = params[:price].to_i * 100
      item.save
    end
  end

以上

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