Last active
March 17, 2021 01:21
-
-
Save kamipo/a53bdfbc72033d7d45346661e9de9ee9 to your computer and use it in GitHub Desktop.
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
ActiveRecord::Schema.define do | |
create_table :posts, force: true do |t| | |
end | |
create_table :comments, force: true do |t| | |
t.integer :post_id | |
end | |
end | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
class_attribute :default_association_scopes, instance_writer: false, instance_predicate: false, default: [] | |
def self.default_association_scope(&scope) | |
self.default_association_scopes += [scope] | |
end | |
def self.inherited(klass) | |
super | |
klass.relation_delegate_class(ActiveRecord::Associations::CollectionProxy).class_eval do | |
def self.new(*) | |
relation = super | |
default_association_scopes = relation.klass.default_association_scopes | |
unless default_association_scopes.empty? | |
default_association_scopes.inject(relation) do |scope, default_scope| | |
scope.merge!(scope.instance_exec(&default_scope)) | |
end | |
end | |
relation | |
end | |
end | |
end | |
end | |
class Post < ApplicationRecord | |
has_many :comments | |
end | |
class Comment < ApplicationRecord | |
belongs_to :post | |
default_association_scope { | |
p proxy_association.owner # => #<Post id: 1> | |
self | |
} | |
end | |
class AssociationTest < Minitest::Test | |
def test_stuff | |
post = Post.create! | |
post.comments | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment