Merging of scopes not working as expected? #12711

Closed
tkoenig opened this Issue Oct 31, 2013 · 4 comments

Projects

None yet

4 participants

@tkoenig

The Rails Guides for Active Record say the following about merging in the chapter Scopes:

If we do want the last where clause to win then Relation#merge can be used .

This seems to work for simple queries, but not for more complex conditions like using .not:

class Asset < ActiveRecord::Base
  scope :active, -> { where deleted_at: nil }
  scope :stored, -> { where stored: true }
end
Loading development environment (Rails 4.0.0)
> Asset.active.merge(Asset.where.not(deleted_at: nil)).to_sql
 => "SELECT "assets".* FROM "assets"  WHERE "assets"."deleted_at" IS NULL AND ("assets"."deleted_at" IS NOT NULL)" 
> Asset.stored.merge(Asset.where(stored: false)).to_sql
 => "SELECT "assets".* FROM "assets"  WHERE "assets"."stored" = 'f'" 
2.0.0p0 :009 > Asset.stored.merge(Asset.where.not(stored: true)).to_sql
 => "SELECT "assets".* FROM "assets"  WHERE "assets"."stored" = 't' AND ("assets"."stored" != 't')" 
> Asset.active.merge(Asset.where(deleted_at: Time.now.yesterday..Time.now)).to_sql
 => "SELECT "assets".* FROM "assets"  WHERE "assets"."deleted_at" IS NULL AND ("assets"."deleted_at" BETWEEN '2013-10-30 11:29:00.994868' AND '2013-10-31 11:29:00.995028')" 

Is this a bug or expected behavior?

@tkoenig

might be related to #10643

@dmathieu

merge takes arel nodes and merges them all together. The actual SQL query is built by arel afterwards.
Therefore, I'm not sure this is actually an ActiveRecord bug, but rather an arel one.

cc @jonleighton

@rafaelfranca rafaelfranca modified the milestone: 4.0.5, 4.0.4, 4.0.6 Mar 10, 2014
@rails-bot rails-bot added the stale label Aug 19, 2014
@rails-bot

This issue has been automatically marked as stale because it has not been commented on for at least
three months.

The resources of the Rails team are limited, and so we are asking for your help.

If you can still reproduce this error on the 4-1-stable, 4-0-stable branches or on master,
please reply with all of the information you have about it in order to keep the issue open.

Thank you for all your contributions.

@rafaelfranca rafaelfranca modified the milestone: 4.0.10, 4.1.7 Aug 21, 2014
@rails-bot rails-bot closed this Nov 19, 2014
@rails-bot

This issue has been automatically closed because of inactivity.

If you can still reproduce this error on the 4-1-stable, 4-0-stable branches or on master,
please reply with all of the information you have about it in order to keep the issue open.

Thank you for all your contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment