Sort a list of objects by property on a linked object

Is it possible to sort the list of objects by the property of the associated object?

For example, with the following class

class RosterSlot < ActiveRecord::Base
  belongs_to :event
  belongs_to :skill
  belongs_to :person
end

I want to do something like RosterSlot.find (: all ,: order => skill.name)

which means that activerecord must do the join and order.

Any ideas?

+3
source share
2 answers

Yes, you can use the: include option to connect.

RosterSlot.find(:all, :include => [:skill], :order => "skills.name ASC")

The: order option accepts a SQL fragment, so skills are a reference to the name of a multiple database table.

The: include accepts an array of active record associations.

. http://www.railsbrain.com/api/rails-2.3.2/doc/index.html?a=M002313&name=find.

+4

.

RosterSlot.all.sort { |x,y| x.skill.name <=> y.skill.name }

, db , , , ActiveRecord:: Base find.

+3

Source: https://habr.com/ru/post/1708264/


All Articles