lundi 21 septembre 2015

How to retrieve sorted entries from many-to-many rich association in rails?

Let's say I have a many-to-many rich association between queues and dudes:

Queue:

has_many in_queue_positionings
has_many dudes, through: in_queue_positionings

Dude:

has_many in_queue_positionings
has_many queues, through: in_queue_positionings

InQueuePositioning has position column in the table and

scope :sorted, lambda { order('BY position ASC') } defined in the model. Let's assume that I always need to access Queue.dudes sorted by positions.

I can access dudes like this:

queue.in_queue_positionings.sorted.each { |pos| pos.dude }

But this method is ugly(and it might also be slow). So how can this problem be solved elegantly and efficiently?

Aucun commentaire:

Enregistrer un commentaire