This project is archived and is in readonly mode.

#2227 ✓resolved
claudiob (at gmail)

[VERIFIED] batches: :conditions for each are applied to each Model.find within the each loop

Reported by claudiob (at gmail) | March 13th, 2009 @ 09:56 AM | in 2.x

Consider the following code:


# app/models/song.rb
class Song < ActiveRecord::Base
  def self.print_pairs(name)
    Song.each(:conditions => ['name = ?', name]) do |song|
        puts song[:name]
        another_song = Song.first(:conditions => ['name <> ?', name])
        puts another_song[:name]
      end
    end
end

I would call it by passing a song name, and it would print out the name of the same song, and the name of another song (with a different name). After applying patch #2201, the .each function has become .find_each

The problem that I have found is that the :conditions applied to Song.each (line 4) is also automatically applied to the Song.first (line 6), and as a consequence Song.first returns an error, since it cannot find a song that matches both conditions ['name = ?', name] and ['name <> ?', name].

I understand that the solution to this problem is to call the inside find as following (line 6):


another_song = Song.with_exclusive_scope { first(:conditions => ['name <> ?', name]) }

However it is not clear whether this is a desired behavior or rather a bug. In this case I have not defined any default_scope for the model Song that has to be overridden by calling with_exclusive_scope, I am just calling Song.find within a Song.each(:conditions) loop.


To replicate this behavior:


rails music
cd music
script/generate scaffold song name:string
rake db:create
rake db:migrate
script/console

Song.create(:name => "Keep The Faith")
Song.create(:name => "Bed Of Roses")
class Song < ActiveRecord::Base
  def self.print_pairs(name)
    Song.each(:conditions => ['name = ?', name]) do |song|
        puts song[:name]
        another_song = Song.with_exclusive_scope { first(:conditions => ['name <> ?', name]) }
        puts another_song[:name]
      end
    end
end
Song.print_pairs('Bed Of Roses')

Once again, the same occurs also after patch #2201, calling .find_each rather than .each, and also using a named_scope to declare the conditions.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>