I am trying to create a Redmine plugin built on Ruby on Rails. I have the following query which fetches the sum of time_entries of all the issues during an invoice.
SELECT SUM( t.hours )
FROM time_entries t
JOIN invoices i ON t.project_id = i.project_id
WHERE t.project_id = <current project id----@project.id>
AND i.id = <billing invoice id>
AND t.updated_on > 'i.created_at'
AND t.updated_on < 'i.due_date'
How can I store this query data inside invoices table column called time_spent or retrieve the results in the invoices view which lists all invoices along with the above query by invoice ID
The associations in model I created goes like this
class Invoice < ActiveRecord::Base
set_table_name "invoices"
set_primary_key "invoice_id"
belongs_to :project
belongs_to :author, :class_name => "User", :foreign_key => "author_id"
has_many :time_entries, :class_name => "TimeEntry", :foreign_key => "project_id"
In the Controller I am calling the model as
@invoices = Invoice.find(:all, :joins=>" INNER JOIN time_entries ON time_entries.project_id = invoices.project_id",:conditions => ["invoices.project_id = ? AND updated_on > ? AND updated_on < ?", @project.id, invoices.created_at, invoices.due_date])
I know the controller instance variable is totally messed up.
Somewhere I doing mistake. Can some one please help me with this.
I'm assuming Rails 3+ and MySQL, this should give you your each item in your @invoices collection an accessor named "time_spent" which will have the sum you are looking for. It will not persist this info in the db, but it retrieves it for your view:
Invoice.where("invoices.project_id = ? AND invoices.updated_on > ? AND invoices.updated_on < ?", @project.id, invoices.created_at, invoices.due_date).select("SELECT invoices.*, SUM( time_entries.hours ) as time_spent").joins(:time_entries).group("invoices.id")
I'm guessing at < Rails 3 below:
Invoice.find(:all,
:conditions => ["invoices.project_id = ? AND updated_on > ? AND updated_on < ?", @project.id, invoices.created_at, invoices.due_date],
:select=>"SELECT invoices.*, SUM( time_entries.hours ) as time_spent",
:joins=>[:time_entries],
:group=>"invoices.id")
(hoping I typed this correctly. If not, the gist is to use the "select" and "group" methods to get your result.)