Last active
December 25, 2015 04:59
-
-
Save mikecmpbll/6921120 to your computer and use it in GitHub Desktop.
has_and_belongs_to_many association with scope not joining correct table in scope.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unless File.exists?('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' | |
# 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 :students do |t| | |
end | |
create_table :groups do |t| | |
t.integer :group_type_id | |
end | |
create_table :groups_students, :id => false do |t| | |
t.integer :group_id, :null => false | |
t.integer :student_id, :null => false | |
end | |
create_table :group_types do |t| | |
t.string :name | |
end | |
end | |
class Student < ActiveRecord::Base | |
has_and_belongs_to_many :groups | |
has_and_belongs_to_many :tutor_groups, -> { merge(Group.filter_type(:tutor_group)) }, class_name: "Group", join_table: "groups_students" | |
has_and_belongs_to_many :tutor_groups2, -> { joins(:group_type).where(group_type: { name: :tutor_group }) } | |
end | |
class Group < ActiveRecord::Base | |
has_and_belongs_to_many :students | |
belongs_to :group_type | |
def self.filter_type(type) | |
joins(:group_type).where(group_types: { name: type }) | |
end | |
end | |
class GroupType < ActiveRecord::Base | |
has_many :groups | |
end | |
class BugTest < Minitest::Test | |
def test_association | |
gt = GroupType.create(name: :tutor_group) | |
g = Group.create | |
g.group_type = gt | |
g.save! | |
s = Student.create | |
s.groups << g | |
s.save! | |
query = Student.includes(:tutor_groups).first | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment