Rails 4, has_many order: via. It just doesn't do anything
I have a situation like this:
class Student < ActiveRecord::Base
has_many :tickets
has_many :movies, through: :tickets
end
class Movie < ActiveRecord::Base
has_many :tickets
has_many :students, through: :tickets
end
class Ticket < ActiveRecord::Base
belongs_to :movie, counter_cache: true
belongs_to :student
end
class Cinema < ActiveRecord::Base
has_many :movies, dependent: :destroy
has_many :students, through: :movies
end
I have this code in my controller ( movie_controller.rb ):
def show
@tickets = @movie.tickets.includes(:student)
end
Now in my grid ( show.html.erb ) I have a situation like this:
<% @tickets.each do |ticket| %>
<tr>
<td><%= ticket.student.id %></td>
<td><%= ticket.student.code %></td>
<td><%= ticket.student.last_name %> <%= ticket.student.first_name %></td>
<td><%= ticket.hours %></td>
<td><% if ticket.payed %>Yes<% else %>No<% end %></td>
</tr>
<% end %>
Now I want to order students by their "last_name, first_name", but if I use this code in my controller:
@tickets = @movie.tickets.includes(:student).order('students.last_name')
in my console I have a SQL query like this:
"AS t0_r0 .... AS t0_r1 ..."
etc. this is normal?
Am I wrong in my logic?
If I use code like this in my model:
class Movie < ActiveRecord::Base
has_many :tickets
has_many :students, -> { order('last_name, first_name') }, through: :tickets
end
nothing works . My list is ordered not by name and name, but by default (id).
How to make it better?
UPDATE
I have changed from the Children model to the Student model.
source to share
"AS t0_r0 .... AS t0_r1 ..." etc .... is this ok? "
Yes, the included features are implemented as an outer join, so the order can be applied to the rows returned from the ticket table.
To use a scope for this, you need to do something like:
student.rb
def self.by_last_name
order(:last_name)
end
ticket.rb
def self.by_student_last_name
joins(:student).merge(Student.by_last_name)
end
... then ...
@tickets = @movie.tickets.by_student_last_name
source to share