ruby-on-rails - 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
时,它说-
不是一种方法。有没有办法更新存储的值?
解决方案
更好的处理方法是
item = Item.find_by(id: params[:id]).value
pluck将返回您的数组,这在您的情况下是不必要的。
推荐阅读
- python - 使用 PySide2 的 Folium 离线地图创建器
- azure-devops - 我应该在管道的power devops工具中放入更新环境变量的名称值对吗?
- java - 在 IntelliJ 中运行的 Tomcat 抛出 UnmarshalException
- mongodb - 我如何在聚合中不敏感地强调大写字母?
- python - Django 结合来自加入两个字典列表的共同值
- c# - 在 C# 中,如何使用大量精美的标记将 POCO 序列化为 XML?
- javascript - 如何知道所有 onload 事件是否已经触发?
- python - 远程运行时谷歌表 api HttpError 429
- javascript - 有一种方法可以监控发送表格时哪些程序需要时间?有没有办法加快速度?(jQuery 验证器)
- gstreamer - Gstreamer 结合不同来源的视频和声音并广播到 RTMP