Skip to content

Instantly share code, notes, and snippets.

@Fustrate
Created December 10, 2020 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fustrate/a2b4736ee17cac0bff9b9bc26e4e64ea to your computer and use it in GitHub Desktop.
Save Fustrate/a2b4736ee17cac0bff9b9bc26e4e64ea to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "rails", "6.1.0"
gem "sqlite3"
end
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 :employees, force: true do |t|
t.boolean :active, default: true
end
create_table :companies, force: true do |t|
t.boolean :active, default: true
end
create_table :companies_assignments, force: true do |t|
t.integer :employee_id
t.integer :company_id
t.string :position
end
end
class Employee < ActiveRecord::Base
# 1. Removing the where clause makes the problem go away, but I _always_ want it scoped like this.
has_many :assignments,
-> { where(companies: { active: true }) },
class_name: "Companies::Assignment"
has_many :companies, through: :assignments do
# 2. Or I could remove the nested condition, but that's the whole point of this method.
def with_position(position)
where(active: true, companies_assignments: { position: position })
end
end
end
module Companies
# 3. Or make the Assignment class not be in a module with a table_name_prefix, but that leads to
# ugly table names and naming clashes in my application.
def self.table_name_prefix
"companies_"
end
class Assignment < ActiveRecord::Base
belongs_to :company
belongs_to :employee
end
end
class Company < ActiveRecord::Base
has_many :assignments, class_name: "Companies::Assignment"
end
class BugTest < Minitest::Test
def test_association_stuff
employee = Employee.create!
company = Company.create!
Companies::Assignment.create!(employee: employee, company: company, position: "manager")
Companies::Assignment.create!(employee: employee, company: company, position: "temp")
assert_equal 2, employee.companies.count
assert_equal 1, employee.companies.with_position("manager").count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment