2012-09-21 86 views
0

我正在将一个手动SQL查询重写为ActiveRecord查询以用于Rails应用程序。ActiveRecord子查询比较作为范围

它做了什么它收集了来自同一个表的两组用户:1名在上周有资格赛(44或48)的用户,以及一个月前有相同资格赛事的用户组。

这是当前查询。我不知道如何将其变成ActiveRecord范围:

select top 500 active_users_last_week.email 
    from (
     select distinct(email) from user_event_tracking 
     where event_id in (44,48) 
     and sitedb_created_date between getdate()-8 and getdate()-1 
     and sitedb_name = 'XYZ' 
     and email not like '%@company.com' 
     and email not like '%@other_company.com' 
    ) active_users_last_week, 
    (
     select distinct(email) from user_event_tracking 
     where event_id in (44,48) 
     and sitedb_created_date between getdate()-60 and getdate()-30 
     and sitedb_name = 'XYZ' 
     and email not like '%@company.com' 
     and email not like '%@other_company.com 
    ) active_users_last_month 
where active_users_last_week.email = active_users_last_month.email; 

有关如何将其变成ActiveRecord范围的任何建议?我已经将这些设置为示波器:

scope :active_events, lambda { 
    where("event_id in (44,48)") 
} 

scope :for_property, lambda { |property| 
    where('sitedb_name = ?', property) 
} 

scope :last_week, lambda { 
    where("sitedb_created_date between GETDATE()-8 and GETDATE()-1") 
} 

scope :last_month, lambda { 
    where("sitedb_created_date between GETDATE()-60 and GETDATE()-30") 
} 

scope :no_test_users, lambda { 
    where("email not like '%@company.com' and email not like '%@other_company.com'") 
} 

示波器都单独工作(以及相互之间)。问题是如何以有效的方式获取Event.active_events.last_weekEvent.active_events.last_month中的电子邮件。

+0

看起来它返回上周仅供网友如果他们在上个月还有资格赛。那是对的吗?什么是型号名称? – iouri

+0

是的,这是完全正确的。该模型被命名为Event。 –

+0

还有一个用户模型?他们如何加入?通过电子邮件? – iouri

回答

0

试试这个:

Event.select(:email).where(:event_id => [44,48], sitedb_created_date => (8.days.ago..1.day.ago), :sitedb_name => 'XYZ', :email => Event.select(:email).where(:event_id => [44,48], sitedb_created_date => (60.days.ago..30.days.ago), :sitedb_name => 'XYZ').where(Event.arel_table[:email].does_not_match_all(["%company.com","%other_company.com"]))) 

您可能需要用几天鼓捣他们调整日期范围,我不知道他们是包容性的或不是100%。您可能需要更改8.days.ago到7.days.ago等

你也应该能够与你的范围要做到这一点:

Event.active_events.last_week.where(:email => Event.active_events.last_month.select(:email)) 
+0

60和30被颠倒,答案更新。 – iouri

+0

太棒了。这很好。感谢你的回答! –