Search code examples
ruby-on-railsarraysgroup-bynamed-scope

Is there a way to create a named scope that groups?


I have the following using 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

I only want @todos to contain a Todo record for a single contact_id (contact_id is an attribute on Todo).

Question: how can I group so that I there is only one record per contact_id in the @todos array?


Solution

  • named_scope supports grouping. Something like this should work:

    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
    

    Then just put this in your controller:

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

    The code may not be exactly right for your app, but you get the idea.