Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Chained where conditions referencing same attribute joined by OR

#6433

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')

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

State: invalid
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Aaron Patterson
    Aaron Patterson
    • State changed from new to invalid
    • Importance changed from to Low

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

    February 15th, 2011 @ 06:33 PM

  2. Jeremy McNevin
    Jeremy McNevin

    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.

    February 15th, 2011 @ 07:16 PM