Chris Rutte Chris Rutte - 1 year ago 61
MySQL Question

How to sort nested items on field in 'parent' model?

I am new to Ruby on Rails and try to make the right query. But after reading the documentation and examples I don't manage to get the right query out of it. So I hope someone can point me in the right direction.

Situation I build an app where trainers can setup trainings, and give these trainings on several dates (the dates are called thrills), other users can subscribe for these thrills. It has the following structure:

class User
has_many :trainings
has_many :thrills, through: :trainings
has_many :reservations

class Training
belongs_to :user
has_many :reservations
has_many :thrills
has_many :users, through: :thrills

class Thrill
belongs_to :training
has_many :reservations
has_many :users, through: :reservations

class Reservation
belongs_to :user
belongs_to :thrill
has_one :training, through: :thrill

How can I make a list of all reservations of the current_user ordered by the thrilldate? The thrilldate is set in the Thrills model.

In my reservations_controller.rb I have:

@reservations = current_user.reservations

This gives the right list of all the reserations, but I want to sort list this on reservation.thrill.thrilldate
I tried so by using this view:

<% @reservations.order("reservation.thrill.thrilldate ASC").each do |reservation| %>

Unfortunately this gives the error:

SQLite3::SQLException: no such column: reservation..thrill.thrilldate: SELECT
"reservations".* FROM "reservations" WHERE "reservations"."user_id" =
? ORDER BY reservation.thrill.thrilldate ASC

Who knows how I can refer to the thrilldate in the Thrills model? Thanks for helping me out!

Answer Source

Assuming thrilldate is a column on Thrill

@reservations = current_user.reservations.joins(:thrill).order('thrills.thrilldate asc')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download