在我的user.rb
文件中
has_many :virtual_transactions
def balance
bought_transactions = VirtualTransaction.where(buyer_id: self.id)
sold_transactions = VirtualTransaction.where(seller_id: self.id)
bought_amount = bought_transactions.inject{|sum, t| sum + t.amount}
sold_amount = sold_transactions.inject{|sum, t| sum + t.amount}
bought_amount - sold_amount
end
在我的virtual_transaction.rb
中
belongs_to :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
def amount
quantity.to_f * stock_price.to_f
end
我正在尝试在不使用balance
列的情况下独立更新买方和卖方的余额。然而,我得到
VirtualTransaction 的未定义方法错误'-'
当我尝试类似的东西时:
User.first.balance
这个想法是分别更新买方的余额和卖方的余额。(卖方递增,买方递减)
如果要执行bought_amount - sold_amount
,则需要使用类似bought_amount.to_i
的方法将bought_amount
从类VirtualTransaction
转换为整数类
def balance
bought_transactions = VirtualTransaction.where(buyer_id: self.id)
sold_transactions = VirtualTransaction.where(seller_id: self.id)
bought_amount = bought_transactions.inject{|sum, t| sum + t.amount}
sold_amount = sold_transactions.inject{|sum, t| sum + t.amount}
bought_amount.to_i - sold_amount.to_i
end
我仍然不知道你的VirtualTransaction
模型是什么样子的,但在尝试进行计算之前,你应该将其转换为整数
更新
@Solias使用def amount
方法将quantity
和stock_price
转换为float
https://ruby-doc.org/core-2.2.0/Float.html您使用的是在sold_amount
和bought_amount
上购买的方法,因此这两个字段应该是float
,并且该类具有-
方法。现在你告诉我,这些值是未定义的变量。因此,您的错误被触发是因为undefined variable
没有浮点数据类型所具有的方法-
。
所以问题是在这两行中听到,返回一个未定义的零变量
bought_amount = bought_transactions.inject{|sum, t| sum + t.amount}
sold_amount = sold_transactions.inject{|sum, t| sum + t.amount}
你需要找到一种方法来正确计算bought_amount
和sold_amount
,记住浮点数的和应该是一个浮点数,所以你可以使用这种方法来进行计算
问题是
bought_amount = nil or undefined
sold_amount = nil or undefined
所以
- sold_amount
不存在,因为nil类没有-
方法
我得走了。祝好运