├── .ruby-version ├── Gemfile ├── .gitignore ├── lib ├── active_record_inherit_assoc │ └── version.rb └── active_record_inherit_assoc.rb ├── gemfiles ├── rails7.1.gemfile ├── rails7.2.gemfile ├── common.rb ├── rails_main.gemfile ├── rails6.1.gemfile └── rails7.0.gemfile ├── .github ├── CODEOWNERS └── workflows │ ├── codeql.yaml │ ├── ci.yml │ ├── rails_main_testing.yml │ └── publish.yml ├── Rakefile ├── CHANGELOG.md ├── active_record_inherit_assoc.gemspec ├── test ├── helper.rb ├── test_belongs_to_association.rb ├── schema.rb ├── test_performance_regression.rb ├── test_inherit_assoc.rb └── test_queries.rb ├── README.md └── LICENSE /.ruby-version: -------------------------------------------------------------------------------- 1 | 3.2.9 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | eval_gemfile('gemfiles/rails6.1.gemfile') 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | pkg/* 2 | .bundle 3 | *.log 4 | localgems 5 | .*.swp 6 | /Gemfile.lock 7 | gemfiles/*.gemfile.lock 8 | -------------------------------------------------------------------------------- /lib/active_record_inherit_assoc/version.rb: -------------------------------------------------------------------------------- 1 | module ActiveRecordInheritAssoc 2 | VERSION = "2.14.0" 3 | end 4 | -------------------------------------------------------------------------------- /gemfiles/rails7.1.gemfile: -------------------------------------------------------------------------------- 1 | eval_gemfile('common.rb') 2 | 3 | gem 'activerecord', '~> 7.1.0' 4 | gem 'sqlite3', '~> 1.4' 5 | -------------------------------------------------------------------------------- /gemfiles/rails7.2.gemfile: -------------------------------------------------------------------------------- 1 | eval_gemfile('common.rb') 2 | 3 | gem 'activerecord', '~> 7.2.0' 4 | gem 'sqlite3', '~> 1.4' 5 | -------------------------------------------------------------------------------- /gemfiles/common.rb: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem 'minitest' 4 | gem 'minitest-rg' 5 | gem 'rake' 6 | gem 'bump' 7 | gem 'byebug' 8 | -------------------------------------------------------------------------------- /gemfiles/rails_main.gemfile: -------------------------------------------------------------------------------- 1 | eval_gemfile('common.rb') 2 | 3 | gem 'activerecord', github: 'rails/rails', branch: 'main' 4 | gem 'sqlite3', '~> 2.0' 5 | -------------------------------------------------------------------------------- /gemfiles/rails6.1.gemfile: -------------------------------------------------------------------------------- 1 | eval_gemfile('common.rb') 2 | 3 | gem 'activerecord', '~> 6.1.0' 4 | gem 'sqlite3', '~> 1.4' 5 | gem 'base64' 6 | gem 'bigdecimal' 7 | gem 'drb' 8 | gem 'mutex_m' 9 | -------------------------------------------------------------------------------- /gemfiles/rails7.0.gemfile: -------------------------------------------------------------------------------- 1 | eval_gemfile('common.rb') 2 | 3 | gem 'activerecord', '~> 7.0.0' 4 | gem 'sqlite3', '~> 1.4' 5 | gem 'base64' 6 | gem 'bigdecimal' 7 | gem 'drb' 8 | gem 'mutex_m' 9 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # CODEOWNERS file 2 | # This file defines who should review code changes in this repository. 3 | # 4 | # Team ownership is managed via Zendesk Identity Governance (ZIG): 5 | # https://github.com/zendesk/zendesk-identity-governance 6 | 7 | * @zendesk/core-gem-owners 8 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require 'bundler/setup' 2 | require 'bundler/gem_tasks' 3 | require 'rake/testtask' 4 | require 'bump/tasks' 5 | 6 | Rake::TestTask.new(:test) do |test| 7 | test.libs << 'lib' << 'test' 8 | test.pattern = 'test/test*.rb' 9 | test.verbose = true 10 | end 11 | 12 | task default: "test" 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | ## [Unreleased] 6 | 7 | ### Changed 8 | - Drop support for Ruby 3.1 and below. Minimum required Ruby version is now 3.2. 9 | 10 | ## [2.14.0] - Previous releases 11 | 12 | See git history for previous changes. 13 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yaml: -------------------------------------------------------------------------------- 1 | name: "CodeQL public repository scanning" 2 | 3 | on: 4 | push: 5 | schedule: 6 | - cron: "0 0 * * *" 7 | pull_request_target: 8 | types: [opened, synchronize, reopened] 9 | workflow_dispatch: 10 | 11 | permissions: 12 | contents: read 13 | security-events: write 14 | actions: read 15 | packages: read 16 | 17 | jobs: 18 | trigger-codeql: 19 | uses: zendesk/prodsec-code-scanning/.github/workflows/codeql_advanced_shared.yml@production 20 | -------------------------------------------------------------------------------- /active_record_inherit_assoc.gemspec: -------------------------------------------------------------------------------- 1 | require_relative "lib/active_record_inherit_assoc/version" 2 | 3 | name = "active_record_inherit_assoc" 4 | 5 | Gem::Specification.new name, ActiveRecordInheritAssoc::VERSION do |s| 6 | s.summary = "Attribute inheritance for AR associations" 7 | s.authors = ["Ben Osheroff"] 8 | s.email = ["ben@gimbo.net"] 9 | s.files = `git ls-files lib`.split("\n") 10 | s.license = "Apache License Version 2.0" 11 | s.homepage = "https://github.com/zendesk/#{name}" 12 | 13 | s.add_runtime_dependency 'activerecord', '>= 6.1' 14 | s.required_ruby_version = '>= 3.2' 15 | end 16 | -------------------------------------------------------------------------------- /test/helper.rb: -------------------------------------------------------------------------------- 1 | require 'bundler/setup' 2 | require 'minitest/autorun' 3 | require 'minitest/rg' 4 | require 'logger' 5 | 6 | require 'active_record' 7 | ActiveRecord::Schema.verbose = false 8 | ActiveRecord::Base.establish_connection( 9 | :adapter => "sqlite3", 10 | :database => ":memory:" 11 | ) 12 | require_relative "schema" 13 | 14 | ActiveSupport.test_order = :random if ActiveSupport.respond_to?(:test_order=) 15 | 16 | def capture_queries(&block) 17 | queries = [] 18 | logger = ->(_n, _s, _f, _id, data) { queries << data[:sql] } 19 | ActiveSupport::Notifications.subscribed(logger, 'sql.active_record', &block) 20 | queries 21 | end 22 | 23 | require 'active_record_inherit_assoc' 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | on: push 3 | jobs: 4 | main: 5 | name: Tests 6 | runs-on: ubuntu-latest 7 | strategy: 8 | fail-fast: false 9 | matrix: 10 | ruby: 11 | - '3.2' 12 | - '3.3' 13 | - '3.4' 14 | gemfile: 15 | - rails6.1 16 | - rails7.0 17 | - rails7.1 18 | - rails7.2 19 | env: 20 | CI: true 21 | BUNDLE_GEMFILE: gemfiles/${{ matrix.gemfile }}.gemfile 22 | steps: 23 | - uses: zendesk/checkout@v3 24 | - uses: zendesk/setup-ruby@v1 25 | with: 26 | ruby-version: ${{ matrix.ruby }} 27 | bundler-cache: true 28 | - run: bundle exec rake test 29 | -------------------------------------------------------------------------------- /.github/workflows/rails_main_testing.yml: -------------------------------------------------------------------------------- 1 | name: Test against Rails main 2 | 3 | on: 4 | schedule: 5 | - cron: "0 0 * * *" # Run every day at 00:00 UTC 6 | workflow_dispatch: 7 | push: 8 | 9 | jobs: 10 | main: 11 | name: Ruby${{ matrix.ruby }} rails_main 12 | runs-on: ubuntu-latest 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | ruby: 17 | - '3.4' 18 | env: 19 | CI: true 20 | BUNDLE_GEMFILE: gemfiles/rails_main.gemfile 21 | 22 | steps: 23 | - uses: zendesk/checkout@v3 24 | - uses: zendesk/setup-ruby@v1 25 | with: 26 | ruby-version: ${{ matrix.ruby }} 27 | bundler-cache: true 28 | - run: bundle exec rake test 29 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to RubyGems.org 2 | 3 | on: 4 | push: 5 | branches: main 6 | paths: lib/active_record_inherit_assoc/version.rb 7 | workflow_dispatch: 8 | 9 | jobs: 10 | publish: 11 | runs-on: ubuntu-latest 12 | environment: rubygems-publish 13 | if: github.repository_owner == 'zendesk' 14 | permissions: 15 | id-token: write 16 | contents: write 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Set up Ruby 20 | uses: ruby/setup-ruby@v1 21 | with: 22 | bundler-cache: false 23 | ruby-version: "3.4" 24 | - name: Install dependencies 25 | run: bundle install 26 | - uses: rubygems/release-gem@v1 27 | -------------------------------------------------------------------------------- /test/test_belongs_to_association.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path '../helper', __FILE__ 2 | 3 | class TestBelongsToAssociation < ActiveSupport::TestCase 4 | class Main < ActiveRecord::Base 5 | end 6 | 7 | class Other < ActiveRecord::Base 8 | belongs_to :main 9 | inherits_from :main, :attr => [:account_id, :val] 10 | end 11 | 12 | def test_value_is_inherited_from_parent 13 | @main = Main.create!(:account_id => 42) 14 | @other = Other.create!(:main => @main) 15 | 16 | assert_equal 42, @other.account_id 17 | end 18 | 19 | def test_multiple_values_are_inherited_from_parent 20 | @main = Main.create!(:account_id => 42, :val => "The Answer") 21 | @other = Other.create!(:main => @main) 22 | 23 | assert_equal 42, @other.account_id 24 | assert_equal "The Answer", @other.val 25 | end 26 | 27 | def test_does_not_inherit_when_parent_not_present 28 | @other = Other.create! 29 | assert_nil @other.account_id 30 | end 31 | 32 | def test_overwrites_value_on_child 33 | @main = Main.create!(:account_id => 42) 34 | @other = Other.create!(:main => @main, :account_id => 1337) 35 | 36 | assert_equal 42, @other.account_id 37 | end 38 | 39 | def test_allows_setting_the_value_after_instantiation 40 | @main = Main.create! 41 | @other = Other.new(:main => @main, :account_id => 1337) 42 | 43 | @main.account_id = 42 44 | @other.save 45 | 46 | assert_equal 42, @other.account_id 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /test/schema.rb: -------------------------------------------------------------------------------- 1 | ActiveRecord::Schema.define(:version => 1) do 2 | drop_table(:mains) rescue nil 3 | create_table "mains" do |t| 4 | t.integer :account_id 5 | t.integer :blah_id 6 | t.string "val" 7 | end 8 | 9 | drop_table(:others) rescue nil 10 | create_table "others" do |t| 11 | t.integer :main_id 12 | t.integer :account_id 13 | t.string :val 14 | end 15 | 16 | drop_table(:thirds) rescue nil 17 | create_table "thirds" do |t| 18 | t.integer :main_id 19 | t.integer :account_id 20 | end 21 | 22 | drop_table(:fourths) rescue nil 23 | create_table "fourths" do |t| 24 | t.integer :main_id 25 | t.integer :account_id 26 | t.integer :blah_id 27 | end 28 | 29 | drop_table(:fifths) rescue nil 30 | create_table "fifths" do |t| 31 | t.integer :main_id 32 | t.integer :account_id 33 | t.integer :sixth_id 34 | end 35 | 36 | drop_table(:sixths) rescue nil 37 | create_table "sixths" do |t| 38 | t.integer :main_id 39 | t.integer :account_id 40 | t.integer :seventh_id 41 | end 42 | 43 | drop_table(:sevenths) rescue nil 44 | create_table "sevenths" do |t| 45 | t.integer :main_id 46 | t.integer :account_id 47 | end 48 | 49 | drop_table(:account) rescue nil 50 | create_table "accounts" do |t| 51 | end 52 | 53 | drop_table(:foos) rescue nil 54 | create_table "foos" do |t| 55 | t.integer :account_id 56 | t.integer :group_id 57 | end 58 | 59 | drop_table(:bars) rescue nil 60 | create_table "bars" do |t| 61 | t.integer :foo_id 62 | t.integer :account_id 63 | end 64 | 65 | drop_table(:bazs) rescue nil 66 | create_table "bazs" do |t| 67 | t.integer :account_id 68 | end 69 | 70 | drop_table(:custom_bar_bazs) rescue nil 71 | create_table "custom_bar_bazs" do |t| 72 | t.integer :bar_id 73 | t.integer :baz_id 74 | t.integer :account_id 75 | end 76 | end 77 | -------------------------------------------------------------------------------- /test/test_performance_regression.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'helper' 4 | require 'minitest/benchmark' 5 | 6 | class Account < ActiveRecord::Base 7 | end 8 | 9 | class Foo < ActiveRecord::Base 10 | has_many :bars, -> { includes :bazs }, dependent: :destroy, inverse_of: :foo, inherit: :account_id 11 | belongs_to :account 12 | end 13 | 14 | class Bar < ActiveRecord::Base 15 | has_many :custom_bar_bazs, inherit: :account_id, inverse_of: :bar, class_name: "CustomBarBazs" 16 | has_many :bazs, through: :custom_bar_bazs, inherit: :account_id 17 | belongs_to :account 18 | belongs_to :foo, inherit: :account_id 19 | end 20 | 21 | class Baz < ActiveRecord::Base 22 | has_many :custom_bar_bazs, dependent: :destroy, inherit: :account_id, inverse_of: :baz, class_name: "CustomBarBazs" 23 | has_many :bars, through: :custom_bar_bazs, inherit: :account_id 24 | belongs_to :account 25 | end 26 | 27 | class CustomBarBazs < ActiveRecord::Base 28 | belongs_to :account 29 | belongs_to :bar 30 | belongs_to :baz 31 | end 32 | 33 | class TestPerformanceRegression < Minitest::Benchmark 34 | def self.bench_range 35 | bench_linear(1, 5, 1) 36 | end 37 | 38 | def setup 39 | skip unless ENV["CI"] 40 | super 41 | 42 | self.class.bench_range.each do |n| 43 | (n * 1000).times do 44 | account = Account.create! 45 | foo = Foo.create!(account_id: account.id, group_id: n) 46 | bar = foo.bars.create 47 | baz = bar.bazs.create 48 | CustomBarBazs.create!(bar_id: bar.id, baz_id: baz.id) 49 | end 50 | end 51 | end 52 | 53 | def bench_performance 54 | assert_performance_linear 0.98 do |n| 55 | Foo.where(group_id: n).includes(:bars).map(&:bars).size 56 | end 57 | end 58 | 59 | def teardown 60 | Account.destroy_all 61 | Foo.destroy_all 62 | Bar.destroy_all 63 | Baz.destroy_all 64 | CustomBarBazs.destroy_all 65 | 66 | super 67 | end 68 | end 69 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ActiveRecord association inheritance 2 | 3 | - Makes models inherit specified attributes from an association. 4 | - Scope queries by inherited attributes 5 | 6 | ## Install 7 | 8 | ``` 9 | gem install active_record_inherit_assoc 10 | ``` 11 | 12 | ## Usage 13 | 14 | ### Filling inherited attributes on initialization: 15 | 16 | ```ruby 17 | # parent_name - The Symbol name of the parent association. 18 | # options - The Hash options to use: 19 | # :attr - A Symbol or an Array of Symbol names of the attributes 20 | # that should be inherited from the parent association. 21 | # 22 | class Post < ActiveRecord::Base 23 | belongs_to :category 24 | inherits_from :category, attr: :account 25 | end 26 | ``` 27 | 28 | ### Scoping queries 29 | 30 | ```ruby 31 | class Post < ActiveRecord::Base 32 | has_many :categories, inherit: :account_id 33 | end 34 | 35 | post = Post.first 36 | post.categories.build.account_id == post.account_id # fills attribute on new objects 37 | post.categories.to_sql # adds inherited attributes to queries 38 | ``` 39 | 40 | This is similar to adding a scope `{ |record| where(account_id: record.account_id) }`, 41 | but also allows to do `Post.all.includes(:categories)` to work by filtering preloaded records. 42 | This will not use the attribute to query, so it might use a different index and find more than neccessary records. 43 | 44 | #### Allowed list of values (inherit_allowed_list) 45 | 46 | In some occasions, there are values that we don't want to filter out, even if they don't correspond to the inherited one. 47 | Following the previous Post example, this could happen if we have a universal "system" category belonging to no account, one that we associated to all the posts that have no other category. A way to keep this category (assuming that it has the account_id `-1`) would look like this: 48 | 49 | ```ruby 50 | class Post < ActiveRecord::Base 51 | has_many :categories, inherit: :account_id, inherit_allowed_list: [-1] 52 | end 53 | ``` 54 | 55 | ### Releasing a new version 56 | A new version is published to RubyGems.org every time a change to `version.rb` is pushed to the `main` branch. 57 | In short, follow these steps: 58 | 1. Update `version.rb`, 59 | 2. update version in all `Gemfile.lock` files, 60 | 3. merge this change into `main`, and 61 | 4. look at [the action](https://github.com/zendesk/active_record_inherit_assoc/actions/workflows/publish.yml) for output. 62 | 63 | To create a pre-release from a non-main branch: 64 | 1. change the version in `version.rb` to something like `1.2.0.pre.1` or `2.0.0.beta.2`, 65 | 2. push this change to your branch, 66 | 3. go to [Actions → “Publish to RubyGems.org” on GitHub](https://github.com/zendesk/active_record_inherit_assoc/actions/workflows/publish.yml), 67 | 4. click the “Run workflow” button, 68 | 5. pick your branch from a dropdown. 69 | 70 | ## Copyright and license 71 | 72 | Copyright 2022 Zendesk 73 | 74 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 75 | You may obtain a copy of the License at 76 | 77 | http://www.apache.org/licenses/LICENSE-2.0 78 | 79 | Unless required by applicable law or agreed to in writing, software distributed under the 80 | License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 81 | See the License for the specific language governing permissions and limitations under the License. 82 | 83 | ## Author 84 | Ben Osheroff 85 | -------------------------------------------------------------------------------- /lib/active_record_inherit_assoc.rb: -------------------------------------------------------------------------------- 1 | require 'active_record' 2 | 3 | module ActiveRecordInheritBuildAssocPrepend 4 | INHERIT_OPTIONS = %i[inherit inherit_allowed_list].freeze 5 | 6 | def valid_options(options) 7 | super + INHERIT_OPTIONS 8 | end 9 | end 10 | 11 | ActiveRecord::Associations::Builder::Association.singleton_class.prepend(ActiveRecordInheritBuildAssocPrepend) 12 | 13 | module ActiveRecordInheritAssocPrepend 14 | def target_scope 15 | if inherited_attributes = attribute_inheritance_hash 16 | super.where(inherited_attributes) 17 | else 18 | super 19 | end 20 | end 21 | 22 | private 23 | 24 | def attribute_inheritance_hash 25 | return nil unless reflection.options[:inherit] 26 | inherit_allowed_list = reflection.options[:inherit_allowed_list] 27 | 28 | Array(reflection.options[:inherit]).each_with_object({}) do |association, hash| 29 | assoc_value = owner.send(association) 30 | assoc_value = Array(assoc_value).concat(inherit_allowed_list) if inherit_allowed_list 31 | hash[association] = assoc_value 32 | hash["#{through_reflection.table_name}.#{association}"] = assoc_value if reflection.options.key?(:through) 33 | end 34 | end 35 | 36 | def skip_statement_cache?(*) 37 | super || !!reflection.options[:inherit] 38 | end 39 | end 40 | 41 | ActiveRecord::Associations::Association.send(:prepend, ActiveRecordInheritAssocPrepend) 42 | 43 | module ActiveRecordInheritPreloadAssocPrepend 44 | def associate_records_to_owner(owner, records) 45 | if inherit = reflection.options[:inherit] 46 | records = Array(records) 47 | filter_associated_records_with_inherit!(owner, records, inherit) 48 | end 49 | super 50 | end 51 | 52 | def build_scope 53 | prescope = super 54 | 55 | if inherit = reflection.options[:inherit] 56 | Array(inherit).each do |inherit_assoc| 57 | owner_values = owners.map(&inherit_assoc) 58 | owner_values.compact! 59 | owner_values.uniq! 60 | owner_values.concat(reflection.options[:inherit_allowed_list]) if reflection.options[:inherit_allowed_list] 61 | prescope = prescope.where(inherit_assoc => owner_values) 62 | end 63 | end 64 | 65 | prescope 66 | end 67 | 68 | def filter_associated_records_with_inherit!(owner, associated_records, inherit) 69 | associated_records.select! do |record| 70 | Array(inherit).all? do |association| 71 | record_value = record.send(association) 72 | record_value == owner.send(association) || reflection.options[:inherit_allowed_list]&.include?(record_value) 73 | end 74 | end 75 | end 76 | end 77 | 78 | ActiveRecord::Associations::Preloader::Association.send(:prepend, ActiveRecordInheritPreloadAssocPrepend) 79 | 80 | class ActiveRecord::Base 81 | # Makes the model inherit the specified attribute from a named association. 82 | # 83 | # parent_name - The Symbol name of the parent association. 84 | # options - The Hash options to use: 85 | # :attr - A Symbol or an Array of Symbol names of the attributes 86 | # that should be inherited from the parent association. 87 | # 88 | # Examples 89 | # 90 | # class Post < ActiveRecord::Base 91 | # belongs_to :category 92 | # inherits_from :category, :attr => :account 93 | # end 94 | # 95 | def self.inherits_from(parent_name, options = {}) 96 | attrs = Array.wrap(options.fetch(:attr)) 97 | 98 | before_validation do |model| 99 | parent = model.send(parent_name) 100 | 101 | attrs.each do |attr| 102 | model[attr] = parent[attr] if parent.present? 103 | end 104 | end 105 | end 106 | end 107 | -------------------------------------------------------------------------------- /test/test_inherit_assoc.rb: -------------------------------------------------------------------------------- 1 | require_relative 'helper' 2 | 3 | class TestInheritAssoc < ActiveSupport::TestCase 4 | class Main < ActiveRecord::Base 5 | attr_accessor :aux 6 | 7 | has_many :others, :inherit => :account_id 8 | has_one :third, :inherit => :account_id 9 | has_many :fourths, :inherit => [:account_id, :blah_id] 10 | has_many :fifths, :inherit => :account_id 11 | has_many :sixths, :through => :fifths, inherit: :account_id 12 | has_many :sevenths, :inherit => :account_id, :inherit_allowed_list => [nil] 13 | end 14 | 15 | class Other < ActiveRecord::Base 16 | belongs_to :main 17 | end 18 | 19 | class Third < ActiveRecord::Base 20 | belongs_to :main 21 | end 22 | 23 | class Fourth < ActiveRecord::Base 24 | belongs_to :main 25 | end 26 | 27 | class Fifth < ActiveRecord::Base 28 | belongs_to :main, inherit: :account_id 29 | belongs_to :sixth, inherit: :account_id 30 | end 31 | 32 | class Sixth < ActiveRecord::Base 33 | belongs_to :main 34 | end 35 | 36 | class Seventh < ActiveRecord::Base 37 | belongs_to :main, inherit: :account_id, inherit_allowed_list: [nil] 38 | end 39 | 40 | describe "Main, with some others, scoped by account_id" do 41 | before do 42 | @main = Main.create! :account_id => 1 43 | Other.create! :main_id => @main.id, :account_id => 1 44 | Other.create! :main_id => @main.id, :account_id => 2 45 | Other.create! :main_id => @main.id, :account_id => 1, :val => "foo" 46 | end 47 | 48 | it "set conditions on simple access" do 49 | assert_equal 2, @main.others.size 50 | end 51 | 52 | it "set conditions on find" do 53 | assert_equal 2, @main.others.all.size 54 | end 55 | 56 | it "merge conditions on find" do 57 | assert_equal 1, @main.others.all.where("val = 'foo'").size 58 | end 59 | 60 | it "merge conditions" do 61 | skip 62 | assert_equal 1, @main.conditional_others.size 63 | end 64 | end 65 | 66 | def test_has_one_should_set_conditions_on_fetch 67 | main = Main.create! :account_id => 1 68 | Third.create! :main_id => main.id, :account_id => 2 69 | third_2 = Third.create! :main_id => main.id, :account_id => 1 70 | 71 | assert_equal third_2, main.third 72 | end 73 | 74 | def test_has_one_should_set_conditions_on_includes 75 | main = Main.create! :account_id => 1 76 | 77 | Third.create! :main_id => main.id, :account_id => 2 78 | third_2 = Third.create! :main_id => main.id, :account_id => 1 79 | 80 | mains = Main.where(id: main.id).includes(:third) 81 | 82 | assert_equal third_2, mains.first.third 83 | end 84 | 85 | def test_has_one_should_set_conditions_on_includes_with_multiple_owners 86 | main_1 = Main.create! :account_id => 1 87 | main_2 = Main.create! :account_id => 1 88 | 89 | Third.create! :main_id => main_1.id, :account_id => 2 90 | third_2 = Third.create! :main_id => main_1.id, :account_id => 1 91 | Third.create! :main_id => main_2.id, :account_id => 2 92 | third_4 = Third.create! :main_id => main_2.id, :account_id => 1 93 | 94 | mains = Main.where(id: [main_1.id, main_2.id]).includes(:third) 95 | 96 | assert_equal third_2, mains.first.third 97 | assert_equal third_4, mains.last.third 98 | end 99 | 100 | def test_has_many_through_should_set_conditions_on_join_table 101 | main_1 = Main.create! :account_id => 1 102 | main_2 = Main.create! :account_id => 1 103 | 104 | sixth_1 = Sixth.create! :main_id => main_1.id, :account_id => 1 105 | sixth_2 = Sixth.create! :main_id => main_1.id, :account_id => 1 106 | sixth_3 = Sixth.create! :main_id => main_1.id, :account_id => 1 107 | sixth_4 = Sixth.create! :main_id => main_1.id, :account_id => 1 108 | 109 | Fifth.create! :main_id => main_1.id, :account_id => 2, :sixth_id => sixth_1.id 110 | Fifth.create! :main_id => main_1.id, :account_id => 1, :sixth_id => sixth_2.id 111 | Fifth.create! :main_id => main_2.id, :account_id => 2, :sixth_id => sixth_3.id 112 | Fifth.create! :main_id => main_2.id, :account_id => 1, :sixth_id => sixth_4.id 113 | 114 | mains = Main.where(id: [main_1.id, main_2.id]) 115 | assert_equal [sixth_2], mains.first.sixths 116 | assert_equal [sixth_4], mains.last.sixths 117 | end 118 | 119 | def test_has_many_should_set_conditions_on_includes 120 | main = Main.create! :account_id => 1, :blah_id => 10 121 | 122 | Fourth.create! :main_id => main.id, :account_id => 2, :blah_id => 10 123 | fourth_2 = Fourth.create! :main_id => main.id, :account_id => 1, :blah_id => 10 124 | 125 | mains = Main.where(id: main.id).includes(:fourths) 126 | 127 | assert_equal [fourth_2], mains.first.fourths 128 | end 129 | 130 | def test_has_many_should_set_conditions_on_includes_with_multiple_owners 131 | main_1 = Main.create! :account_id => 1, :blah_id => 10 132 | main_2 = Main.create! :account_id => 1, :blah_id => 20 133 | 134 | Fourth.create! :main_id => main_1.id, :account_id => 2, :blah_id => 10 135 | fourth_2 = Fourth.create! :main_id => main_1.id, :account_id => 1, :blah_id => 10 136 | Fourth.create! :main_id => main_2.id, :account_id => 2, :blah_id => 20 137 | fourth_4 = Fourth.create! :main_id => main_2.id, :account_id => 1, :blah_id => 20 138 | 139 | mains = Main.where(id: [main_1.id, main_2.id]).includes(:fourths) 140 | 141 | assert_equal [fourth_2], mains.first.fourths 142 | assert_equal [fourth_4], mains.last.fourths 143 | end 144 | 145 | def test_has_many_should_set_conditions_for_multiple_inherits 146 | main = Main.create! :account_id => 1, :blah_id => 10 147 | # these two should match 148 | Fourth.create! :main_id => main.id, :account_id => 1, :blah_id => 10 149 | Fourth.create! :main_id => main.id, :account_id => 1, :blah_id => 10 150 | 151 | # nope. 152 | Fourth.create! :main_id => main.id, :account_id => 1, :blah_id => 5 153 | Fourth.create! :main_id => main.id, :account_id => 1, :blah_id => 12 154 | Fourth.create! :main_id => 99999, :account_id => 1, :blah_id => 12 155 | 156 | assert_equal(2, main.fourths.size) 157 | end 158 | 159 | def test_has_many_should_setup_attributes_when_building 160 | main = Main.create! :account_id => 1, :blah_id => 10 161 | 162 | other = main.others.build 163 | assert_equal main.id, other.main_id 164 | assert_equal main.account_id, other.account_id 165 | end 166 | 167 | def test_has_many_should_setup_attributes_when_creating 168 | main = Main.create! :account_id => 1, :blah_id => 10 169 | 170 | other = main.others.create! 171 | assert_equal main.id, other.main_id 172 | assert_equal main.account_id, other.account_id 173 | 174 | other = main.others.create 175 | assert_equal main.id, other.main_id 176 | assert_equal main.account_id, other.account_id 177 | end 178 | 179 | def test_has_one_should_setup_attributes_when_building 180 | main = Main.create! :account_id => 1, :blah_id => 10 181 | 182 | other = main.build_third 183 | assert_equal main.account_id, other.account_id 184 | 185 | other = main.create_third 186 | assert_equal main.account_id, other.account_id 187 | end 188 | 189 | def test_association_caching_fail 190 | main_1 = Main.create!(account_id: 1) 191 | third_1 = Third.create!(main_id: main_1.id, account_id: 1) 192 | 193 | assert_equal third_1, main_1.third 194 | 195 | main_2 = Main.create!(account_id: 2) 196 | third_2 = Third.create!(main_id: main_2.id, account_id: 2) 197 | 198 | assert_equal third_2, main_2.third # this will fail, commenting out the previous assertion will make it pass. 199 | end 200 | 201 | def test_inherit_allow_nil_in_belongs_to 202 | main_with_account = Main.create!(account_id: 1) 203 | seventh_1 = Seventh.create! :account_id => 1, :main_id => main_with_account.id 204 | assert_equal main_with_account, seventh_1.main 205 | 206 | system_main = Main.create! 207 | seventh_2 = Seventh.create! :account_id => 42, :main_id => system_main.id 208 | assert_equal system_main, seventh_2.main 209 | end 210 | 211 | def test_inherit_allow_nil_in_has_many 212 | main = Main.create!(account_id: 1) 213 | seventh_1 = Seventh.create! :account_id => 1, :main_id => main.id 214 | system_seventh = Seventh.create! :account_id => nil, :main_id => main.id 215 | assert_equal main.sevenths, [seventh_1, system_seventh] 216 | end 217 | end 218 | -------------------------------------------------------------------------------- /test/test_queries.rb: -------------------------------------------------------------------------------- 1 | require_relative 'helper' 2 | 3 | class TestInheritAssocQueries < ActiveSupport::TestCase 4 | class Main < ActiveRecord::Base 5 | has_many :others, :inherit => :account_id 6 | has_one :third, :inherit => :account_id 7 | has_many :fourths, :inherit => [:account_id, :blah_id] 8 | end 9 | 10 | class Other < ActiveRecord::Base 11 | belongs_to :main, :inherit => :account_id 12 | end 13 | 14 | class Third < ActiveRecord::Base 15 | belongs_to :main, :inherit => :account_id 16 | end 17 | 18 | class Fourth < ActiveRecord::Base 19 | belongs_to :main, :inherit => :account_id 20 | end 21 | 22 | describe 'generated sql queries' do 23 | let(:query) { Main.first } 24 | 25 | let(:queries) { 26 | capture_queries { query.to_a } 27 | } 28 | 29 | before do 30 | Main.delete_all 31 | Other.delete_all 32 | Third.delete_all 33 | Fourth.delete_all 34 | 35 | main = Main.create!(account_id: 100, blah_id: 200) 36 | Other.create!(main: main, account_id: 100) 37 | Third.create!(main: main, account_id: 100) 38 | Fourth.create!(main: main, account_id: 100, blah_id: 200) 39 | end 40 | 41 | describe 'has_many' do 42 | describe 'loading a single record' do 43 | let(:query) { Main.first.others } 44 | 45 | it 'correctly inherits' do 46 | assert_equal 2, queries.size 47 | assert_match(/WHERE.*others.\..account_id/i, queries.last) 48 | end 49 | end 50 | 51 | describe 'preloading using .includes' do 52 | let(:query) { Main.includes(:others).all } 53 | 54 | it 'correctly inherits' do 55 | assert_equal 2, queries.size 56 | assert_match(/WHERE.*others.\..account_id/i, queries.last) 57 | end 58 | 59 | describe 'loading many records with different values for the inherited association' do 60 | before do 61 | main = Main.create!(account_id: 777, blah_id: 999) 62 | Other.create!(main: main, account_id: 777) 63 | end 64 | 65 | it 'correctly maps based on inherited association' do 66 | results = query.to_a 67 | 68 | subsequent_queries = capture_queries do 69 | results.each do |main| 70 | others = main.others.to_a 71 | 72 | assert_equal 1, others.size 73 | assert_equal main.account_id, others.first.account_id 74 | end 75 | end 76 | 77 | assert_equal 0, subsequent_queries.size 78 | end 79 | end 80 | end 81 | 82 | describe 'preloading using .preload' do 83 | let(:query) { Main.all.preload(:others) } 84 | 85 | it 'correctly inherits' do 86 | assert_equal 2, queries.size 87 | assert_match(/WHERE.*others.\..account_id/i, queries.last) 88 | end 89 | 90 | describe 'loading many records with different values for the inherited association' do 91 | before do 92 | main = Main.create!(account_id: 777, blah_id: 999) 93 | Other.create!(main: main, account_id: 777) 94 | end 95 | 96 | it 'correctly maps based on inherited association' do 97 | results = query.to_a 98 | 99 | subsequent_queries = capture_queries do 100 | results.each do |main| 101 | others = main.others.to_a 102 | 103 | assert_equal 1, others.size 104 | assert_equal main.account_id, others.first.account_id 105 | end 106 | end 107 | 108 | assert_equal 0, subsequent_queries.size 109 | end 110 | end 111 | end 112 | end 113 | 114 | describe 'has_one' do 115 | describe 'loading a single record' do 116 | let(:query) { Main.first.third } 117 | 118 | let(:queries) { 119 | capture_queries { query } 120 | } 121 | 122 | it 'correctly inherits' do 123 | assert_equal 2, queries.size 124 | assert_match(/WHERE.*thirds.\..account_id/i, queries.last) 125 | end 126 | end 127 | 128 | describe 'preloading using .includes' do 129 | let(:query) { Main.includes(:third).all } 130 | 131 | it 'correctly inherits' do 132 | assert_equal 2, queries.size 133 | assert_match(/WHERE.*thirds.\..account_id/i, queries.last) 134 | end 135 | 136 | describe 'loading many records with different values for the inherited association' do 137 | before do 138 | main = Main.create!(account_id: 777, blah_id: 999) 139 | Third.create!(main: main, account_id: 777) 140 | end 141 | 142 | it 'correctly maps based on inherited association' do 143 | results = query.to_a 144 | 145 | subsequent_queries = capture_queries do 146 | results.each do |main| 147 | assert_equal main.account_id, main.third.account_id 148 | end 149 | end 150 | 151 | assert_equal 0, subsequent_queries.size 152 | end 153 | end 154 | end 155 | 156 | describe 'preloading using .preload' do 157 | let(:query) { Main.preload(:third).all } 158 | 159 | it 'correctly inherits' do 160 | assert_equal 2, queries.size 161 | assert_match(/WHERE.*thirds.\..account_id/i, queries.last) 162 | end 163 | 164 | describe 'loading many records with different values for the inherited association' do 165 | before do 166 | main = Main.create!(account_id: 777, blah_id: 999) 167 | Third.create!(main: main, account_id: 777) 168 | end 169 | 170 | it 'correctly maps based on inherited association' do 171 | results = query.to_a 172 | 173 | subsequent_queries = capture_queries do 174 | results.each do |main| 175 | assert_equal main.account_id, main.third.account_id 176 | end 177 | end 178 | 179 | assert_equal 0, subsequent_queries.size 180 | end 181 | end 182 | end 183 | end 184 | 185 | describe 'has_many with multiple inherits' do 186 | describe 'loading a single record' do 187 | let(:query) { Main.first.fourths } 188 | 189 | it 'correctly inherits' do 190 | assert_equal 2, queries.size 191 | assert_match(/WHERE.*fourths.\..account_id/i, queries.last) 192 | assert_match(/WHERE.*fourths.\..blah_id/i, queries.last) 193 | end 194 | end 195 | 196 | describe 'preloading using .includes' do 197 | let(:query) { Main.includes(:fourths).all } 198 | 199 | it 'correctly inherits' do 200 | assert_equal 2, queries.size 201 | assert_match(/WHERE.*fourths.\..account_id/i, queries.last) 202 | assert_match(/WHERE.*fourths.\..blah_id/i, queries.last) 203 | end 204 | 205 | describe 'loading many records with different values for the inherited association' do 206 | before do 207 | main = Main.create!(account_id: 777, blah_id: 999) 208 | Fourth.create!(main: main, account_id: 777, blah_id: 999) 209 | end 210 | 211 | it 'correctly maps based on inherited association' do 212 | results = query.to_a 213 | 214 | subsequent_queries = capture_queries do 215 | results.each do |main| 216 | fourths = main.fourths.to_a 217 | 218 | assert_equal 1, fourths.size 219 | assert_equal main.account_id, fourths.first.account_id 220 | end 221 | end 222 | 223 | assert_equal 0, subsequent_queries.size 224 | end 225 | end 226 | end 227 | 228 | describe 'preloading using .preload' do 229 | let(:query) { Main.all.preload(:fourths) } 230 | 231 | it 'correctly inherits' do 232 | assert_equal 2, queries.size 233 | assert_match(/WHERE.*fourths.\..account_id/i, queries.last) 234 | assert_match(/WHERE.*fourths.\..blah_id/i, queries.last) 235 | end 236 | 237 | describe 'loading many records with different values for the inherited association' do 238 | before do 239 | main = Main.create!(account_id: 777, blah_id: 999) 240 | Fourth.create!(main: main, account_id: 777, blah_id: 999) 241 | end 242 | 243 | it 'correctly maps based on inherited association' do 244 | results = query.to_a 245 | 246 | subsequent_queries = capture_queries do 247 | results.each do |main| 248 | fourths = main.fourths.to_a 249 | 250 | assert_equal 1, fourths.size 251 | assert_equal main.account_id, fourths.first.account_id 252 | end 253 | end 254 | 255 | assert_equal 0, subsequent_queries.size 256 | end 257 | end 258 | end 259 | end 260 | end 261 | end 262 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS --------------------------------------------------------------------------------