【发布时间】:2015-09-25 09:33:45
【问题描述】:
我有这种情况:
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) 控制器中有这段代码:
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 %>
现在我想按学生的“姓氏,名字”排序,但如果我在控制器中使用此代码:
@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) 排序的。
如何做得更好?
更新:
我从模型“儿童”变成了“学生”。
【问题讨论】:
-
Children类应该是Child例如'child'.pluralize #=> 'children'; 'children'.pluralize #=> 'children'; 'children'.singularize #=> 'child'。 Rails 从关联名称中推断出类名和表名(使用复数和单数化等方法),因此如果您必须使用子类作为类名,那么您需要告诉关联,例如has_many :childrens, class_name: 'Children'...` 不确定您的表格是什么样的,但您可能还需要添加primary和foreign键。 -
您可以尝试使用
reorder('childrens.last_name ASC')代替您当前的.order()吗? ;"AS t0_r0 .... AS t0_r1 ..."是 Rails 为表连接生成的名称(t0_r0是表 0 行 0 的别名)。在您的 SQL 查询中使用joins/includes生成这个是完全正常的 -
@engineersmnky,我用 Children >> Student 编辑了这个问题。
标签: ruby-on-rails ruby performance ruby-on-rails-4 rails-activerecord