Skip to content

Instantly share code, notes, and snippets.

@pier-oliviert
Last active August 29, 2015 14:18
Show Gist options
  • Select an option

  • Save pier-oliviert/080f7f01b0dcf62562d7 to your computer and use it in GitHub Desktop.

Select an option

Save pier-oliviert/080f7f01b0dcf62562d7 to your computer and use it in GitHub Desktop.
class Tag
def posts
post_scope = ->(tag) { where '? = ANY (posts.tags)', tag.id }
options = {}
reflection = ActiveRecord::Reflection::HasManyReflection.new(:posts, post_scope, options, self.class)
association = PostsAssociation.new(self, reflection)
@posts ||= ActiveRecord::Associations::CollectionProxy.new(Post, association)
end
private
class PostsAssociation < ActiveRecord::Associations::HasManyAssociation
def scope(opts = {})
Post.where('? = ANY (posts.tags)', owner.id).published
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment