Joining Tables
# Join Through Defined Associations (Inner Join): Category.joins(:articles) Article.joins(:category, :comments) |
# Outer Joins: Author.left_outer_joins(:posts).distinct.select('authors., COUNT(posts.) AS posts_count').group('authors.id') |
# N + 1 queries problem: Always use .includes() Article.includes(:category, :comments).where(comments: { visible: true }) |
# Join Using Raw SQL: Author.joins("INNER JOIN posts ON posts.author_id = authors.id AND posts.published = 't'") |
# Retrieving filtered data from multiple tables: If you want to call order multiple times, subsequent orders will be appended to the first. Person .select('people.id, people.name, comments.text') .joins(:comments) .where('comments.created_at > ?', 1.week.ago) |
# Retrieving specific data from multiple tables: Person .select('people.id, people.name, companies.name') .joins(:company) .find_by('people.name' => 'John') # this should be the last |
Comments
Related