gpt4 book ai didi

ruby-on-rails-3 - 我可以将这个 Rails 计算插入数据库吗?

转载 作者:行者123 更新时间:2023-12-01 11:54:01 25 4
gpt4 key购买 nike

我试图通过在数据库而不是应用程序层中进行工作来提高我的应用程序的效率,我想知道我是否可以将此计算移到数据库中。

模型:

class Offer < ActiveRecord::Base
has_many :lines
has_many :items, :through => :lines
end

class Line < ActiveRecord::Base
belongs_to :offer
belongs_to :item
# also has a 'quantity' attribute (integer)
end

class Item < ActiveRecord::Base
has_many :lines
has_many :offers, :through => :lines
# also has a 'price' attribute (decimal)
end

我想做的是计算出价。目前我在 Offer 类中有一个价格方法:

def price
self.lines.inject(0) do |total, line|
total + line.quantity * line.item.price
end
end

我怀疑可以进行 Offer.sum 计算,而不是直接从数据库中获取答案,而不是循环遍历记录,但是 Calculations section of the ActiveRecord query guide没有足够的细节来帮助我。有人吗?

谢谢!

最佳答案

你是对的,你可以用 sum 做到这一点.像这样:

class Offer < ActiveRecord::Base
# ...

def price
self.lines.sum 'lines.quantity * items.price', :joins => :item
end
end

当您调用时Offer.find( some_id ).price 上面的代码将构造一个类似这样的查询:

SELECT SUM( lines.quantity * items.price ) AS total
FROM lines
INNER JOIN items ON items.id = lines.item_id
WHERE lines.offer_id = <some_id>
;

关于ruby-on-rails-3 - 我可以将这个 Rails 计算插入数据库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8767964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com