首页 > 解决方案 > Rails 中的减法

问题描述

我有一个具有整数类型属性的对象。我想在特定操作后从属性中减去 1。我在控制器中试过:

  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

我得到:

NoMethodError (undefined method `to_i' for [40]:Array

当我删除to_i时,它说-不是一种方法。有没有办法更新存储的值?

标签: ruby-on-rails

解决方案


更好的处理方法是

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

pluck将返回您的数组,这在您的情况下是不必要的。


推荐阅读