activerecord-hackery / squeel

Active Record, improved. Live again :)
http://erniemiller.org/2013/11/17/anyone-interested-in-activerecord-hackery/
MIT License
2.4k stars 214 forks source link

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

Open hbd225 opened 9 years ago

hbd225 commented 9 years ago

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!