Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails polymorphic with includes based on type of class

Let's say we have these models

class Message
  belongs_to :messageable, polymorphic: true
end

class Ticket
  has_many :messages, as: :messageable
  has_many :comments
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
end

class Rating
  belongs_to :user
end

class Comment
  belongs_to :ticket
end

Now I want to load all messages (which have associated tickets or users), and eager load depending on the type of class, either comments for tickets and ratings for users

Of course Message.includes(:messageable).order("created_at desc") will only include the directly associated object, but the question would be how to include the different association types that derive from each model type (i.e. in this example, how to eager load comments for tickets and ratings for users)?

This is just a simple example, but what about even more complicated cases, where I'd like to include something else for the user, another association, and what if that association needs more includes?

like image 710
Andrei S Avatar asked Feb 26 '13 18:02

Andrei S


1 Answers

The only way I can think of to do this is to duplicate the associations on each model with a common name:

class Ticket
  has_many :messages, as: :messageable
  has_many :comments
  has_many :messageable_includes, class_name: "Comment"
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
  has_many :messageable_includes, class_name: "Rating"
end

Message.includes(:messageable => :messageable_includes) ...

I'm not sure I would use this strategy as a widespread solution, but if this is a complicated as your case gets, it may work for you.

like image 196
Zach Kemp Avatar answered Oct 23 '22 23:10

Zach Kemp