0
0

More than 3 years have passed since last update.

【Rails】TypeError (nil can't be coerced into Integer):の対処法

Posted at

症状

RailsAPIモードでメソッド作成し叩いたところ、以下のエラーが表示されてしまいました。

翻訳すると、「TypeError(nilを整数に強制変換することはできません):」でした。
nilを整数に変換しようとして、失敗しているようです。

error
Completed 500 Internal Server Error in 21ms (ActiveRecord: 0.4ms | Allocations: 18292)



TypeError (nil can't be coerced into Integer):

app/controllers/hoges_controller.rb:112:in `+'
app/controllers/hoges_controller.rb:112:in updateHoge

該当のメソッドは以下です。

paramsからidを受け取り、DBからHogeを検索。
その検索したHogeのvaluationとparamsからvaluationを受けとり、その二つの値の平均値を再度Hogeに更新するメソッドです。

Hoge.rb
def  updateHoge
  hoge = Hoge.find(params[:hoge_id])

  newValuation = hoge.valuation + params[hoge_valuate]
  newValuation = newValuation / 2  

  if hoge.update!(:valuation newValuation)
    render json: {
      hoge: hoge
    },status: :ok
  else
    render json: {},status: :ng    
  end
end

解決方法

paramsで受け取るときの指定先を修正したら、解決しました。
paramsから受け取るときに指定先が間違っていると「nil」になり、nilとintegerの値を足そうとしていたため、エラーになっていました。

Hoge.rb
def  updateHoge
  hoge = Hoge.find(params[:hoge_id])

  //integer + nilになっているためエラーだった
  newValuation = hoge.valuation + params[hoge_valuation]
  newValuation = newValuation / 2  

  if hoge.update!(:valuation newValuation)
    render json: {
      hoge: hoge
    },status: :ok
  else
    render json: {},status: :ng    
  end
end
0
0
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
0
0