This project is archived and is in readonly mode.

#6433 ✓invalid
Jeremy McNevin

Chained where conditions referencing same attribute joined by OR

Reported by Jeremy McNevin | February 15th, 2011 @ 05:53 PM

I've noticed that in Rails 3.0.4, the where method behaves differently if the attribute it references has been used previously, generating an 'OR' instead of 'AND'. Is this expected behavior?

Rails 3.0.3
State.where(:abbreviation => 'TX').where(:abbreviation => 'NE')
SQL: SELECT states.* FROM states WHERE (states.abbreviation = 'TX') AND (states.abbreviation = 'NE')

Rails 3.0.4
State.where(:abbreviation => 'TX').where(:abbreviation => 'NE')
SQL: SELECT states.* FROM states WHERE (states.abbreviation = 'TX' OR states.abbreviation = 'NE')

Comments and changes to this ticket

  • Aaron Patterson

    Aaron Patterson February 15th, 2011 @ 06:33 PM

    • State changed from “new” to “invalid”
    • Importance changed from “” to “Low”

    This is expected behavior that fixes #4598. The OR will only be generated when the keys are the same. An AND with identical columns doesn't make sense.

  • Jeremy McNevin

    Jeremy McNevin February 15th, 2011 @ 07:16 PM

    I'm not sure I'm in agreement with this.

    I would expect the where method to operate in consistent manner, and not swap AND or OR around in any case, even if the SQL being generated "doesn't make sense." I could see using chained where statements referencing the same attribute to limit the set of records I ultimately want to search.

    UNICAMERAL_STATES = ['NE']
    class State < ActiveRecord::Base
    scope :unicameral, where(:abbreviation => UNICAMERAL_STATES) end
    State.unicameral.where(:abbreviation => 'MN') # None found.

    Granted, someone might be able to come up with a better example than that. I guess the issue is, should chaining where statements together by default actually be able to increase the number of results that are being returned? I think using OR in this case is an unsafe assumption.

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>

Pages