Skip to content

Instantly share code, notes, and snippets.

@kamipo
Last active March 17, 2021 01:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamipo/a53bdfbc72033d7d45346661e9de9ee9 to your computer and use it in GitHub Desktop.
Save kamipo/a53bdfbc72033d7d45346661e9de9ee9 to your computer and use it in GitHub Desktop.
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