nsommer
nsommer

Reputation: 283

Rails: Order model object by attribute of referenced model object

consider having a model 'album' and a model 'artist'. albums have a reference to an artist.

I want to get an array of all albums, sorted by the name of the artist of the album and the albums release year.

In plain SQL, it would look like that:

SELECT a1.name,a1.release_year,a2.name from albums a1 INNER JOIN artists a2 ON a1.artist_id=a2.id ORDER BY a2.name ASC, a1.release_year;

I'm new to ruby and to rails and couldn't find a solution for doing so with rails' methods. I know the order method of model objects and successfully used it to sort objects by an attribute.

However, I don't know how to sort not only by an attribute of the model itself, but also by an attribute of a referenced model (in this case: the name of 'artist').

Thanks for your answers.

Upvotes: 2

Views: 274

Answers (1)

Surya
Surya

Reputation: 16002

Try this:

Album.joins(:artist).order('artists.name ASC, release_year')

or:

Album.joins(:artist).order('artists.name ASC, albums.release_year')

or:

Album.joins(:artist).order("#{Artist.table_name}.name ASC, #{Album.table_name}.release_year")

Probably you can create a scope for much easier access to this call in your Album model class:

scope :artist_with_release_year, -> { joins(:artist).order("#{Artist.table_name}.name ASC, #{Album.table_name}.release_year") }

Which you can call later in your app:

Album.artist_with_release_year

Upvotes: 2

Related Questions