Skip to content

Instantly share code, notes, and snippets.

@BenEddy
Last active December 14, 2015 02:39
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 BenEddy/5015196 to your computer and use it in GitHub Desktop.
Save BenEddy/5015196 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
has_many :tasks
def self.with_flagged_comments
includes(:task).merge(Task.with_flagged_comments)
end
end
class Task < ActiveRecord::Base
belongs_to :user
has_many :comments
def self.with_flagged_comments
includes(:comment).merge(Comment.flagged)
end
end
class Comment < ActiveRecord::Base
belongs_to :task
def self.flagged
where(:flagged => true)
end
end
# User does not have the :comments association
User.with_flagged_comments
=> User.includes(:task).includes(:comments).where("comments.flagged = true")
=> "Association missing"
# What we want
=> User.includes(:task => :comments).where("comments.flagged = true")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment