Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3.2: Chaining lambda scopes?
    primarykey
    data
    text
    <p>In my Rails 3.2.8 app I have some named scopes I would like to chain together in some circumstances.</p> <p>So, for example, I have these two scopes:</p> <pre><code>scope :by_status, lambda { |status| if status == "All" then WorkRequest.all else WorkRequest.find_all_by_status(status) end } scope :in_date_range, lambda { |start_date, end_date| includes([:person, :pier_module]).where("(status_date &gt;= ?) AND (status_date &lt;= ?)", start_date, end_date) } </code></pre> <p>I use them separately, but I'd also like to be able to call them together like this:</p> <pre><code>WorkRequest.by_status("Accepted").in_date_range("2012-01-01", "2012-10-02") </code></pre> <p>When I try that it complains that in_date_range is not a method of Array.</p> <p>But I have another scope, </p> <pre><code>scope :active, includes([:person, :pier_module]).where("status = 'New Request'") </code></pre> <p>and if I do</p> <pre><code>WorkRequest.active.in_date_range("2012-01-01", "2012-10-02") </code></pre> <p>it works! Apparently the active scope returns a Relation, whereas the lambda scopes return Arrays, and so can't be chained.</p> <p>I'd love to know why the difference between simpler scopes and lambda scopes, how the parameters affect it, and whether there's anything I can do short of writing a combined scope, which I've done.</p> <pre><code>scope :by_status_in_date_range, lambda { |status, start_date, end_date| includes([:person, :pier_module]).where("(status = ?) AND (status_date &gt;= ?) AND (status_date &lt;= ?)", status, start_date, end_date) } </code></pre> <p>Works, but not very DRY (since I need the individual scopes, too) or Rails-ish. Searching here and elsewhere I've seen similar questions but none that seem to apply to this situation, where I'm trying to chain two lambdas with parameters.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload