Tom Brunoli
Tom Brunoli

Reputation: 3466

Rails eager load with has_and_belongs_to_many

I've got two models, Post and Tag, that are associated using has_and_belongs_to_many. I have an action to loads the posts for a specific tag, and I would like to eagerly load each post's other tags.

I tried using

has_and_belongs_to_many :posts, -> { includes :tags }

on the Tag model, and tried using

@posts = @tag.posts.where(approved: true).includes(:tags)

in the controller action, but in both cases, N+1 queries were run when rendering

post.tags.pluck(:name).join(', ')

in the view.

Is there something I'm doing wrong, or am I not able to use eager loading when referring to the same table?

Upvotes: 2

Views: 1729

Answers (1)

zkcro
zkcro

Reputation: 4344

From a quick play in the console, it seems like pluck does it's own database call. You should instead get the names from the eager-loaded tags some other way, for example using map:

post.tags.map{ |tag| tag.name }.join(', ')

Upvotes: 2

Related Questions