Note that there are some explanatory texts on larger screens.

plurals
  1. POScope vs Class Method in Rails 3
    text
    copied!<p>Based on the Rails 3 API, the difference between a scope and a class method is almost non-existent.</p> <pre><code>class Shipment &lt; ActiveRecord::Base def self.unshipped where(:shipped =&gt; false) end end </code></pre> <p>is the same as</p> <pre><code>scope :unshipped, where(:shipped =&gt; false) </code></pre> <p>However, I'm finding that I'm sometimes getting different results using them.</p> <p>While they both generate the same, correct SQL query, the scope doesn't always seem to return the correct values when called. It looks like this problem only occurs when its called the same way twice, albeit on a different shipment, in the method. The second time it's called, when using scope it returns the same thing it did the first time. Whereas if I use the class method it works correctly.</p> <p>Is there some sort of query caching that occurs when using scope?</p> <p>Edit:</p> <pre><code>order.line_items.unshipped </code></pre> <p>The line above is how the scope is being called. Orders have many line_items.</p> <p>The generate_multiple_shipments method is being called twice because the test creates an order and generates the shipments to see how many there are. It then makes a change to the order and regenerates the shipments. However, group_by_ship_date returns the same results it did from the first iteration of the order.</p> <pre><code>def generate_multiple_shipments(order) line_items_by_date = group_by_ship_date(order.line_items.unshipped) line_items_by_date.keys.sort.map do |date| shipment = clone_from_order(order) shipment.ship_date = date line_items_by_date[date].each { |line_item| shipment.line_items &lt;&lt; line_item } shipment end end def group_by_ship_date(line_items) hash = {} line_items.each do |line_item| hash[line_item.ship_date] ||= [] hash[line_item.ship_date] &lt;&lt; line_item end hash end </code></pre>
 

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