Skip to content

Instantly share code, notes, and snippets.

@jturkel
Created January 10, 2016 03:58
Show Gist options
  • Select an option

  • Save jturkel/09beb87f273453d7639f to your computer and use it in GitHub Desktop.

Select an option

Save jturkel/09beb87f273453d7639f to your computer and use it in GitHub Desktop.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
# Schema
ActiveRecord::Schema.define do
ActiveRecord::Base.connection.create_table(:blogs) do |t|
end
ActiveRecord::Base.connection.create_table(:posts) do |t|
t.integer :blog_id
t.string :title
end
end
# Models
class Blog < ActiveRecord::Base
has_many :posts
has_many :filtered_posts, -> do
from("(select * from posts where title like '%post2') as posts")
end, class_name: 'Post'
end
class Post < ActiveRecord::Base
belongs_to :blog
end
class BugTest < Minitest::Test
def test_scope_with_from
blog = Blog.create!
blog.posts.create!(title: 'blog1-post1')
blog.posts.create!(title: 'blog1-post2')
assert_equal(1, blog.filtered_posts.to_a.size)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment