开发者

Using Rails/AR to generate this complex query

In trying to solve a grouping and ordering problem (original question here: "Complex" grouping and indexing in rails?), I got a SQL query that will fetch the right records the right way.

My qu开发者_C百科estion now is: how do I generate this SQL query using Rails/AR synthax?

The SQL-query is as follows:

SELECT
u.id as owner_id, u.name as owner_name, t.id, t.due_date
FROM users u
INNER JOIN tasks m ON u.id = m.owner_id
INNER JOIN tasks t ON u.id = t.owner_id
GROUP BY u.id, u.name, t.id, t.due_date
ORDER BY MIN(m.due_date), t.due_date


I think you'll need to play around with your database and these attributes to get it just right, but you could try something like this.

class User < ActiveRecord::Base
   has_one :next_task, :class_name => :task, :order => "due_date desc", :limit => 1
   has_many :tasks, :order => "due_date desc"

end

class Task < ActiveRecord::Base
    belongs_to :user

end

User.include([:next_task,:tasks]).order("task.due_date desc").tasks.each { |task|
      puts task.user.owner_id 
      puts task.user.owner_name
      puts task.due_date
}

I'm not sure about the order clause to sort the users... you'll have to inspect the SQL generated to determine exactly what needs to be there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜