Skip to content
This repository has been archived by the owner on Mar 30, 2022. It is now read-only.

default_scope applying incorrect scope when using has_many :through association #368

Open
hbd225 opened this issue Mar 19, 2015 · 0 comments

Comments

@hbd225
Copy link

hbd225 commented Mar 19, 2015

Hi,

When using default_scope and has_many :through association, squeel seems to apply incorrect scope.
Here is a reproduction script.

gem 'activerecord', '4.2.0'
gem 'squeel', '1.2.3'
require 'active_record'
require 'minitest/autorun'
require 'logger'
require 'squeel'

# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :users, force: true do |t|
  end

  create_table :posts, force: true do |t|
    t.integer :user_id
    t.boolean :active
  end

  create_table :comments, force: true do |t|
    t.integer :post_id
  end
end

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments, through: :posts
end

class Post < ActiveRecord::Base
  has_many :comments

  default_scope { where { active == true } }
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

class BugTest < Minitest::Test
  def test_default_scope
    user = User.create!
    user.posts << Post.create!
    user.posts.first.comments << Comment.create!

    assert_equal 1, user.comments.count
    assert_equal 1, Comment.count
  end
end

squeel applied active == true to Comment so that this test failed and got following error.

ActiveRecord::StatementInvalid: SQLite3::SQLException: 
no such column: comments.active: 
SELECT COUNT(*) FROM "comments" 
INNER JOIN "posts" ON "comments"."post_id" = "posts"."id" 
WHERE "comments"."active" = 't' AND "posts"."user_id" = ?

Please let me know if there is anything I can help.

Thanks!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant