Rails Multiplying value of afcolumn using ActiveRecord

一曲冷凌霜 提交于 2019-12-12 05:17:39

问题


I want to multiply a value of an specific column considering the user id.

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.

Ok, then I added two animals for user 1 (id 1) and 1 animal for user 2 (id 2)

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') 

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.


回答1:


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)

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)

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}
   }



回答2:


I just figured out the solution:

Animal.group('user_id').sum('3*mensal_cost')

the group was the key :D



来源:https://stackoverflow.com/questions/38963829/rails-multiplying-value-of-afcolumn-using-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!