Skip to content

Instantly share code, notes, and snippets.

@8parth
Created January 23, 2017 10:44
Show Gist options
  • Save 8parth/27400963f350000c5811a461c7303ae3 to your computer and use it in GitHub Desktop.
Save 8parth/27400963f350000c5811a461c7303ae3 to your computer and use it in GitHub Desktop.
has_many :through association with specific conditions
# user.rb
# simple
has_many :posts, dependent: :destroy # all posts
has_many :published_posts, -> { where(published: true) }, class_name: "Post" # all published posts
# advanced
has_many :comments, through: :posts, dependent: :destroy
has_many :comments_on_published_posts, through: :published_posts, dependent: :destroy # comments on published posts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment