从SQL查询中更改活动记录查询

时间:2011-11-09 15:08:05

标签: sql ruby-on-rails ruby-on-rails-3 activerecord

我的SQL有点生疏,但我设法让这段sql工作......

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

我想知道的是将这个sql语句转换为可以在rails上的ruby中使用的东西。所以可以引用一个活动的记录查询,可能是......

@records = Effort.find(:all,:select => etc ...

问题是我似乎无法解决如何做到这一点,因为我是ruby on rails的新手。

更新

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

2 个答案:

答案 0 :(得分:1)

我假设你正在使用Ruby on Rails 3,因为这个问题被标记了,所以这里是语法:

 Effort.select('project_id, taskType, user_id, SUM(hours)')
       .joins(:project_task)
       .where(:project_tasks => {:project_id => 2, :taskType => 'Pre-Sales'})
       .group('user_id')

我的解决方案和你的sql语句的主要区别在于它将使用JOIN而不仅仅是两个表之间的条件。您还应该为列引用添加前缀,以确保不会发生冲突:

.group("#{Effort.quoted_table_name}.user_id")

这是未经测试的,所以看看它是否像您期望的那样发挥作用。

答案 1 :(得分:0)

如果要使用ActiveRecords在rails中实现sql,可以使用范围

前:

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,“售前”)

我个人没试过,但应该工作

HTH

sameera