命名范围与find_by_sql(具体示例)

时间:2009-12-04 15:19:14

标签: ruby-on-rails named-scope

出于好奇,有没有人知道使用命名范围构建以下集合的更好方法(而不是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 个答案:

答案 0 :(得分:0)

我没有测试过这个,但我认为它会起作用:

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"
                      }
                    ]
  }    
}

(我的回答的先前版本将子选择分解为自己的查询,我认为这是不必要的。)