ruby-on-rails - Rails 4, order in has_many :through. 它什么都不做

标签 ruby-on-rails ruby performance ruby-on-rails-4 rails-activerecord

我有这种情况:

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

我的 (movie_controller.rb) Controller 中有这段代码:

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

现在在我的网格中(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 %>

现在我想按学生的“last_name, first_name”对他们进行排序,但是如果我在我的 Controller 中使用此代码:

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

在我的控制台中,我有一个像这样的 SQL 查询:

"AS t0_r0 .... AS t0_r1 ..." 等等... 正常吗?

我的逻辑错了吗?

如果我在我的模型中使用这样的代码:

class Movie < ActiveRecord::Base
    has_many :tickets
    has_many :students, -> { order('last_name, first_name') }, through: :tickets
end

没有效果。我的列表不是按姓氏和名字排序,而是默认 (id)。

如何做得更好?

更新:

我从模型“ child ”更改为“学生”。

最佳答案

""AS t0_r0 .... AS t0_r1 ..."等等...是否正常?"

是的,include 已作为外部连接实现,因此 order by 可以应用于从 tickets 表返回的行。

要为此使用作用域,您需要执行类似的操作:

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

……然后……

@tickets = @movie.tickets.by_student_last_name

关于ruby-on-rails - Rails 4, order in has_many :through. 它什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276317/

相关文章:

ruby - block 中局部变量的作用域

ruby-on-rails - rails : Find rows without connection in HABTM relation

c++ - std::move() 作为性能瓶颈?

java - 在 Java 中反转字符串最有效的算法是什么?

ruby-on-rails - Rails 3 内置的 rake 任务,它们位于哪里?

mysql - 哪个是 Rails 应用程序的最佳数据库?

ruby-on-rails - 不知道如何构建任务 'rails'

ruby - 强制 Psych 读取 YAML 映射作为给定类的对象

java - HashMap vs ArrayList 性能我是正确的

javascript - 如何改进我使用 Textmate for Ruby on Rails、HTML、CSS 和 Javascript 的方式?