views:

225

answers:

1

Just out of curiosity, does anyone know a better way of building the following collection using named scopes (as opposed to find_by_sql)?

@available = Workflow.find_by_sql(["
      SELECT workflows.id FROM workflows
      WHERE workflows.project_id = ? AND workflows.status < 5 AND
      ( workflows.created_by = ? OR workflows.id IN 
        (
           SELECT workflow_id FROM workflow_histories   
           INNER JOIN workflow_recipients on workflow_histories.id = workflow_recipients.workflow_history_id   
           WHERE workflow_recipients.recipient_id = ? AND workflow_recipients.recipient_type = ?
        )
      )", project.id, @current_user.id,  @current_user.id , 'USER'])
+1  A: 

I haven't tested this, but I think it would work:

named_scope :available, lambda { |user_id, project_id|
  { :select => :id,
    :conditions =>  [ "project_id = :project_id AND status < 5 AND
                       (created_by = :user_id OR id IN (
                         SELECT workflow_id FROM workflow_histories   
                         INNER JOIN workflow_recipients ON workflow_histories.id = workflow_recipients.workflow_history_id   
                         WHERE workflow_recipients.recipient_id = :user_id AND workflow_recipients.recipient_type = :recipient_type
                       )",
                      { :user_id        => user_id,
                        :project_id     => project_id,
                        :recipient_type => "USER"
                      }
                    ]
  }    
}

(A previous version of my answer breaks the sub-select out into its own query, which I think is unnecessary.)

Jordan
Thanks man, that's exactly what I needed. Only thing that needed changing was a missing closing parenthesis
Maximus
Wow, I've been working with ActiveRecord for a while now and I never realized you could use named parameters instead of just positional using '?'. That's cool.
Jeff Whitmire