Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient ActiveRecord has_and_belongs_to_many query

I have Page and Paragraph models with a has_and_belongs_to_many relation. Given a paragraph_id, I'd like to get all matching pages. e.g.:

pages = Paragraph.find(paragraph_id).pages.all

However, this takes two queries. It can be done in one query:

SELECT "pages".* FROM "pages" 
INNER JOIN "pages_paragraphs" ON "pages_paragraphs"."page_id" = "pages"."id" 
WHERE "pages_paragraphs"."paragraph_id" = 123

But can this be done without

  • using find_by_sql
  • without modifications to the page_paragraphs table (e.g. adding an id).

Update:

My page model looks like this:

class Page < ActiveRecord::Base
  has_and_belongs_to_many :paragraphs, uniq: true
end
like image 844
Michiel de Mare Avatar asked Nov 29 '12 11:11

Michiel de Mare


People also ask

What are ActiveRecord methods?

The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save.

What is Has_and_belongs_to_many?

Rails offers two different ways to declare a many-to-many relationship between models. The first way is to use has_and_belongs_to_many, which allows you to make the association directly: The second way to declare a many-to-many relationship is to use has_many :through.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...


2 Answers

With a has_many :through relationship, you could use this:

pages = Page.joins(:pages_paragraphs).where(:pages_paragraphs => {:paragraph_id => 1})

Take a look at Specifying Conditions on the Joined Tables here: http://guides.rubyonrails.org/active_record_querying.html

If you want the pages and paragraphs together:

pages = Page.joins(:pages_paragraphs => :paragraph).includes(:pages_paragraphs => :paragraph).where(:pages_paragraphs => {:paragraph_id => 1})

With a has_and_belongs_to_many:

pages = Page.joins("join pages_paragraphs on pages.id = pages_paragraphs.page_id").where(["pages_paragraphs.paragraph_id = ?", paragraph_id])
like image 54
John Naegle Avatar answered Oct 05 '22 01:10

John Naegle


You can use eager_load for this

pages = Paragraph.eager_load(:pages).find(paragraph_id).pages

I found an article all about this sort of thing: 3 ways to do eager loading (preloading) in Rails 3 & 4 by Robert Pankowecki

like image 25
Toby 1 Kenobi Avatar answered Oct 05 '22 03:10

Toby 1 Kenobi