2010-11-04 103 views
1

我有以下使用searchlogic:有沒有辦法創建一個分組的命名範圍?

@todos = Todo.contact_user_id_is(current_user). 
       contact_campaign_id_is(@campaign). 
       current_date_lte(Date.today). 
       done_date_null. 
       ascend_by_current_date 

我只想@todos包含單個CONTACT_ID一個日程記錄(CONTACT_ID上的Todo的屬性)。

問題:我該如何分組,以便每個contact_id在@todos數組中只有一條記錄?

回答

1

named_scope支持分組。像這樣的東西應該工作:

class Todo < ActiveRecord::Base 

    belongs_to :contact 

    named_scope :one_per_contact, lambda{ |user, campaign| 
    { 
     :joins => :contact, 
     :conditions => ['contacts.user_id = ? AND contacts.campaign_id = ? AND todos.current_date <= ? AND todos.done_date IS NULL', user.id, campaign.id, Date.today], 
     :group => 'todos.contact_id' 
     :order => :current_date 
    } 
    } 

end 

然後只是把這個在你的控制器:

@todos = Todo.one_per_contact(current_user, @campaign) 

的代碼可能不完全適合您的應用程序,但你的想法。

+0

lemme給它一個結果我會給你發送結果...男人,仍然試圖理解lambdas – Angela 2010-11-04 15:19:32

+0

嗨,所以我注意到這使用條件爲用戶和活動 - 但searchlogic命名範圍已經這樣做.. ..我仍然需要這些額外的命名範圍工作? – Angela 2010-11-05 02:14:41

+0

這個命名的作用域應該沒有任何額外的searchlogic作用域。但是您也可以刪除這些條件並鏈接searchlogic命名範圍。在這種情況下,我會將它全部保留在命名範圍中,因爲它執行一個非常特定的功能。 – aNoble 2010-11-05 15:45:57

相關問題