Jonathan Clark
Jonathan Clark

Reputation: 20538

Making sum on join tables

I am creating a Rails 3.2 web app. In this app I got four tables. Project, Task, Article and Item.

What I want to do is to get all the task values (prices from article) summed up in a single call.

This is what I tried and it works, but is it the best way of doing it?

@project.tasks.where("status = ?", "completed").joins(:articles).sum(:price)

Task table

class Task < ActiveRecord::Base

 has_many :articles
 has_many :items, :through => :articles

end

Article Join Table

class Article < ActiveRecord::Base

 belongs_to :task
 belongs_to :item

 attr_accessible :account_id, :amount, :price, :item_id, :task_id

end

Item table

class Item < ActiveRecord::Base

 has_many :articles
 has_many :tasks, :through => :articles

end

Upvotes: 1

Views: 2588

Answers (1)

rmagnum2002
rmagnum2002

Reputation: 11421

to sum it up it looks ok the way you did it, but also you can prettify your code:

project.rb

has_many :completed_tasks, class: 'Task', :conditions => {:status => 'completed'}

controller

@project.completed_tasks.joins(:articles).sum(:price)

Upvotes: 5

Related Questions