squeel icon indicating copy to clipboard operation
squeel copied to clipboard

has_many :through: default_scope on join table is applied incorrectrly

Open TatianaTyu opened this issue 12 years ago • 4 comments

I have Articles and Authors connected n-to-n as follows:

class Article < ActiveRecord::Base
  has_many :authorships
  has_many :authors, through: :authorships
end

class Author < ActiveRecord::Base
  has_many :authorships
  has_many :articles, through: :authorships
end

class Authorship < ActiveRecord::Base
  belongs_to :author
  belongs_to :article
  default_scope -> { where(primary: true) }  # !!!
end

Note that there is a default_scope defined for Authorship. Now when I call author.articles, this scope is incorrectly applied to Article rather than Authorship.

>>author.articles.to_sql
"SELECT "articles".* FROM "articles" INNER JOIN "authorships" ON "articles"."id" = "authorships"."article_id" WHERE "articles"."primary" = 't' AND "authorships"."author_id" = $1"

When I remove Squeel from the Gemfile, the SQL query becomes correct.

Ruby 2.0.0 Rails 4.0.1 Squeel 1.1.1 or edge (tried both) I am using PorstgreSQL: pg (0.17.1)

# Gemfile
ruby '2.0.0'
source 'https://rubygems.org'
gem 'rails', '4.0.1'
gem 'pg'
gem "squeel", :git => "git://github.com/ernie/squeel.git"

TatianaTyu avatar Jan 17 '14 21:01 TatianaTyu

#migration

create_table :articles do |t|
  t.string :name
  t.timestamps
end

create_table :authors do |t|
  t.string :name
  t.timestamps
end

create_table :authorships do |t|
  t.boolean :primary
  t.references :article
  t.references :author
  t.timestamps
end

TatianaTyu avatar Jan 17 '14 21:01 TatianaTyu

Also referenced here:

https://github.com/rails/rails/issues/11843

aaronchi avatar Jan 22 '14 23:01 aaronchi

Hi @aaronchi @kira-corina I confirmed that it was a bug and fixed it on master branch. Please have a try. Thank you all :)

bigxiang avatar Jul 18 '14 06:07 bigxiang

@bigxiang thanks! Tested in the following environment: ruby 2.1.2 rails 4.0.5 pg 0.17.1 squeel edge

TatianaTyu avatar Jul 18 '14 16:07 TatianaTyu