简体   繁体   English

Rails 4,命令has_many:through。 它什么都不做

[英]Rails 4, order in has_many :through. It simply does nothing

I have this situation: 我有这种情况:

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 ( movie_controller.rb ) controller: 我在我的( movie_controller.rb )控制器中有这个代码:

def show
  @tickets = @movie.tickets.includes(:student)
end

Now in my grid ( show.html.erb ) I have this situation: 现在在我的网格( show.html.erb )中我遇到这种情况:

<% @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 the students by their "last_name, first_name", but if I use this code in my controller: 现在我想通过他们的“last_name,first_name”命令学生,但如果我在我的控制器中使用此代码:

@tickets = @movie.tickets.includes(:student).order('students.last_name')

in my console I have a SQL query like this: 在我的控制台中,我有一个像这样的SQL查询:

"AS t0_r0 .... AS t0_r1 ..." and so on... is it normal? "AS t0_r0 .... AS t0_r1 ..."等等......这是正常的吗?

Is my logic wrong? 我的逻辑错了吗?

If I use in my model a code like this: 如果我在我的模型中使用这样的代码:

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 last name and first name, but default (id). 我的列表不是按姓氏和名字排序,而是默认(id)。

How to do better? 怎么做得更好?

UPDATE : 更新

I changed from model "Children" to "Student". 我从模特“儿童”改为“学生”。

""AS t0_r0 .... AS t0_r1 ..." and so on... is it normal?" “”AS t0_r0 .... AS t0_r1 ......“等等......这是正常的吗?”

Yes, the includes has been implemented as an outer join, so the order by can be applied to the rows returned from the tickets table. 是的,包已经实现为外连接,因此order by可以应用于从ticket表返回的行。

To use scope for this, you'd want 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM