Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Joining with scopes #42

Open
donjar opened this issue Dec 21, 2016 · 0 comments
Open

Joining with scopes #42

donjar opened this issue Dec 21, 2016 · 0 comments

Comments

@donjar
Copy link

donjar commented Dec 21, 2016

Issue

I cannot join with scopes. As far as I know I am able to do so with Squeel.

Reproduction

require 'bundler/inline'
require 'minitest/spec'
require 'minitest/autorun'

gemfile true do
  source 'https://rubygems.org'
  gem 'activerecord', '~> 4.2.7.1' # which Active Record version?
  gem 'sqlite3'
  gem 'baby_squeel', github: 'rzane/baby_squeel'
end

ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')

ActiveRecord::Schema.define do
  create_table :dogs, force: true do |t|
    t.integer :weight
  end
end

class Dog < ActiveRecord::Base
  scope :double_weight, -> { select(:id).select('2 * weight AS double_weight') }
end

class BabySqueelTest < Minitest::Spec
  it 'works' do
    scope = Dog.joining { Dog.double_weight.as(double_weight).on { id = double_weight.id } }

    scope.to_sql.must_equal %{
      SELECT "dogs".* FROM "dogs" INNER JOIN (SELECT "dogs"."id", 2 * weight as double_weight FROM "dogs") double_weight ON "dogs"."id" = "double_weight"."id"
    }.squish
  end
end

This returns:
BabySqueel::NotFoundError: There is no column or association named 'double_weight' for Dog.

If I use Squeel instead:

rails _4.2.7.1_ new try
cd try
echo "gem 'squeel'" >> Gemfile
bundle
bin/rails g model Dog weight:integer
bin/rake db:migrate

Then add scope :double_weight, -> { select(:id).select('(2 * weight) AS double_weight') } into app/models/dog.rb.

Afterwards, run bin/rails c. Running
Dog.joins { Dog.double_weight.as(double_weight).on { id = double_weight.id } } works.

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

No branches or pull requests

2 participants