Tom Brunoli
Tom Brunoli

Reputation: 3466

Eagerly load many to many associations in Sequel

I'm writing an application and I have two models, a Post and a Tag model. They have a many-to-many association. I would like to load all of the tags for a post when retrieving a post, so I don't have to run multiple trips to the DB.

The models look roughly like this (i've omitted some private details):

class Post < Sequel::Model
  many_to_many :tags
end

class Tag < Sequel::Model
  many_to_many :posts
end

I have tried Post.eager_graph(:tags)[id], which had some success, but it only loaded the first tag and prefixed all the tag column names with tags_ instead of chucking it in to an array or something. Is there a way to have it load all of the tags at once, or am I going to have to keep them separate queries?

Thanks for your help!

Upvotes: 2

Views: 527

Answers (1)

Jeremy Evans
Jeremy Evans

Reputation: 12139

Unless you are eagerly loading multiple posts, it makes no sense to automatically load the tags when retrieving posts. It's going to take multiple queries anyway unless you JOIN, and I'm guessing a JOIN is going to be slower than two separate queries when considering the additional overhead required by Sequel to split the JOINed results.

Upvotes: 2

Related Questions