My SQL is alittle bit rusty but ive managed to get this piece of sql that works...
Select project_id, taskType, user_id, SUM(hours)
From project_tasks, efforts
where project_tasks.id = efforts.project_task_id and project_tasks.project_id = 2 and project_tasks.taskType = "Pre-Sales"
group by user_id
what i want know is to transfer this sql statement into something that can be used in ruby on rails. So an active record query that can be referenced, probably along the lines of ..
@records = Effort.find(:all, :select => etc...
the problem is i cant seem to the work out how this can be done as i am new to ruby on rails.
Update
class Effort < ActiveRecord::Base
belongs_to :project_task
belongs_to :project
belongs_to :user
end
class ProjectTask < ActiveRecord::Base
belongs_to :project
has_many :efforts
end
I'm assuming you're using Ruby on Rails 3 since this question is tagged with it, so here's the syntax:
Effort.select('project_id, taskType, user_id, SUM(hours)')
.joins(:project_task)
.where(:project_tasks => {:project_id => 2, :taskType => 'Pre-Sales'})
.group('user_id')
The major difference with my solution and your sql statement is that this will utilize a JOIN rather than just a condition between the two tables. You should also table prefix the column references to ensure no clashing occurs:
.group("#{Effort.quoted_table_name}.user_id")
This is untested so see if it acts as you'd expect.
If you want to implement your sql in rails with ActiveRecords, you could use scope
Ex:
class Effort < ActiveRecord::Base
belongs_to :project_task
belongs_to :project
belongs_to :user
scope :all_records, lambda { |project_id, task_type
{
:select => "project_id, taskType, user_id, SUM(hours) ",
:from => "project_tasks, efforts",
:where => "project_tasks.id = efforts.project_task_id and project_tasks.project_id =#{project_id} and project_tasks.taskType = '#{task_type}'",
:group => "user_id"
}
}
end
@records = Effort.all_records(2,"Pre-Sales")
I haven't tried this personally but should work
HTH
sameera
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.