使用ActiveRecord将Afcolumn乘以Rails的值 [英] Rails Multiplying value of afcolumn using ActiveRecord
问题描述
我要考虑用户ID乘以特定列的值。
I want to multiply a value of an specific column considering the user id.
假设我有一个表 users
,其中包含用户1(id 1)和用户2(id 2),以及具有名称
的表动物
和 mensal_cost
。
Assume I have a table users
with user 1 (id 1) and user 2 (id 2), and a table animals
which has name
and mensal_cost
.
好,然后我为用户1(id 1)添加了两个动物,为用户1添加了动物2(id 2)
Ok, then I added two animals for user 1 (id 1) and 1 animal for user 2 (id 2)
我想知道如何使用 ActiveRecord
计算 mensal_cost
3个月后增加相同的基本值,这意味着我必须将实际值乘以3。
I want to know how I can using ActiveRecord
calculates the mensal_cost
income after 3 months increasing the same base value, it means I have to multiply the actual value by 3.
我正在尝试某些方法像这样:
I'm trying something like this:
Animal.where(user_id: ?).sum('3*mensal_cost')
由于我不知道可以存在多少个用户,因此我必须写一个电话,该电话将为每个用户ID列出之后的金额3个月。
Since I don't know how many users can exist, I must write a call which will list for each user id the amount after 3 months.
推荐答案
好吧,您几乎自己拥有了它-只是一些小细节可以像这样:
Ok, you nearly had it on your own - just the minor details can be like this:
user_ids = [id1, id2]
full_sum = 3 * Animal.where(:user_id => user_ids).sum(:mensal_cost)
注意:请记住,求和后可以乘以三等于将每个数字乘以3,例如
Note: don't forget you can multiply by three after summing and it'll be the same as summing each one multiplied by 3 eg
(3 * 2)+(3 * 3)+(3 * 4)== 3 *(2 + 3 + 4)
(3 * 2) + (3 * 3) + (3 * 4) == 3 * (2 + 3 + 4)
或您可以遍历用户以获取其个人总和,如下所示:
or you can iterate through the users to get their individual sums like so:
mensal_sums = {}
user_ids = [id1, id2]
user_ids.each do |user_id|
mensal_sums[user_id] = 3 * Animal.where(:user_id => user_id).sum(:mensal_cost)
end
puts mensal_sums
=> {id1 => 63, id2 => 27}
编辑
以及您想要用户名的位置:
EDIT and one where you want the user name as well:
mensal_sums = {}
users = User.find([id1, id2])
users.each do |user|
mensal_sums[user.id] = {:user_name => user.name,
:sum => (3 * user.animals.sum(:mensal_cost)) }
end
puts mensal_sums
=> {id1 => {:user_name => "Bob Jones", :sum => 63},
id2 => {:user_name => "cJane Brown", :sum =>27}
}
这篇关于使用ActiveRecord将Afcolumn乘以Rails的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!