Using Rails/AR to generate this complex query

心不动则不痛 提交于 2019-12-23 01:40:11

问题


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 question 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

回答1:


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.



来源:https://stackoverflow.com/questions/5543792/using-rails-ar-to-generate-this-complex-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!