Subtraction in Rails

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Subtraction in Rails



I am very new to Rails and currently face an issue about subtraction in Rails. I have an object that has an integer type of attribute but I want to subtract 1 from the attribute after finishing a particular action but I am getting NoMethodError (undefined methodto_i' for [40]:Arrayerror and when I removedto_iit is saying-` is not a method. Is there any way that I can update the stored value?


NoMethodError (undefined method


error and when I removed


it is saying



Here is what I have tried:



Controller


def subtraction
#find a item and get the value, let's say value is 40
item = Item.where(id: params[:id]).pluck(:value)

# subtract 1 from the value and i thought it would be 40-1
after_subtraction = item.to_i - 1

#update the value
final = item.update(value: after_subtraction)
end




2 Answers
2



You can't directly convert array in to to_i . please use below method


after_subtraction = item.join.to_i - 1



The better way to handle is


item = Item.find_by(id: params[:id]).value



pluck will return you array, which is not necessary in your case here.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard