ruby on rails - Using scope to calculate SUM from two tables -
i have 2 db tables next fields:
log_lines: id, user_id, date fragments: id, log_line_id, amount corresponding models:
models/log_lines.rb
class logline < activerecord::base has_many :fragments, dependent: :destroy def total_amount fragments.sum(:amount) end end models/fragments.rb
class fragment < activerecord::base belongs_to :log_line end i want amount sum depending user_id. sql query job:
select sum(f.amount) log_lines ll left bring together fragments f on f.log_line_id = ll.id ll.user_id = 74123;
i've created total_amount method in logline model , calling logline controller:
amount = 0 ll_list = logline.where(:user_id => user_id) ll_list.each { |ll| amount += ll.total_amount } actually works, think not efficient way implement it. because many database queries executed during such collection of data.
would possible implement via 1 scope?
this possible via 1 scope. use:
class logline < activerecord::base scope :user_amount, ->(user_id) { select('sum(fragments.amount') .joins('left bring together fragments on fragments.log_line_id = log_line.id') .where('log_line.user_id = ?', user_id) } end another way it:
class logline < activerecord::base scope :user_amount, ->(user_id) { joins('left bring together fragments on fragments.log_line_id = log_line.id') .where(fragments: { user_id: user_id }) .sum('fragments.amount') } end ruby-on-rails ruby-on-rails-4
No comments:
Post a Comment