2011-04-12 67 views
1

我正在使用rails 2.3.10和新的named_scope。我正在处理一个SQL,它会检索特定事件的最后一个邀请列表。我想出了一个带子查询的SQL,看起来它可以做我想做的事。我在考虑是否可以使用named_scope来做同样的事情,以便我可以使用find()如何将自我表子查询SQL转换为Rails的named_scope?

我有以下问题:

  1. 是否有可能实现与named_scope的SQL?
  2. 它可以在一个优雅的方式,使子选择不包括在:condition?多个named_scope需要?
  3. named_scope(s)是怎么样的?
  4. find()如何包含name_scope(s)?

SQL:

SELECT * 
    FROM invitation inv1 
    JOIN (
     SELECT event_id, user_id, MAX(invite_time) AS last_invite_time 
      FROM invitation 
      GROUP BY event_id, user_id 
     ) AS last_invite ON 
     inv1.event_id = last_invite.event_id AND 
     inv1.user_id = last_invite.user_id AND 
     inv1.invite_time = last_invite.last_invite_time 

邀请数据:

event_id  user_id  invite_time  invite_reply_code 
1   78   2011-02-01 15:21 1 
2   78   2011-02-02 11:45 1 
2   79   2011-02-02 11:50 1 
2   79   2011-02-02 11:55 1 
2   80   2011-02-02 11:50 1 
2   80   2011-02-02 11:51 1 

预期结果:

event_id  user_id  invite_time  invite_reply_code 
2   78   2011-02-02 11:45 1 
2   79   2011-02-02 11:55 1 
2   80   2011-02-02 11:51 1 

回答

0

find:joins选项可以接受字符串,它将只是坚持进入SQL。为了让您的event_id在那里,你将需要使用lambda,所以这样的事情是你追求的:

named_scope :foo, lambda { |event_id| 
    { :select => "oinv.*", 
    :from => "invitation AS oinv" 
    :joins => <<-SQL 
     JOIN (
      SELECT event_id, user_id, MAX(invite_time) AS last_invite_time 
       FROM invitation AS jinv 
       GROUP BY event_id, user_id 
      ) AS last_invite ON 
      oinv.event_id  = last_invite.event_id AND 
      oinv.user_id  = last_invite.user_id AND 
      oinv.invite_time = last_invite.last_invite_time 
     SQL 
    , :conditions => [ "oinv.event_id = ?", event_id ] 
    } 
} 

这是完全未经测试,但希望你能看到我在做什么,这套你在正确的道路上。