繁体   English   中英

对表中的关联列进行排序

[英]Sorting associated column in table

我尝试根据228个可排序表列进行可排序列

一切都正确,但是我不知道如何对其他模型的关联列进行排序。

# Table name: vacations
#  id        :integer          not null, primary key
#  start_at  :date             not null
#  end_at    :date             not null
#  person_id :integer          not null

我尝试使用此:

  = sortable "person.first_name", "Employee"

这不正确。

社团协会

class Vacation < ActiveRecord::Base   
belongs_to :person 
end

class Person < ActiveRecord::Base
has_many :vacations
end

人员表的架构:

# Table name: people
#
#  id                         :integer          not null, primary key
#  pesel                      :string           not null
#  first_name                 :string           not null
#  last_name                  :string           not null

VacationsController中的当前索引操作。

def index
    @vacations = Vacation.order(sort_column + ' ' + sort_direction)
                         .paginate(page: params[:page], per_page: 20)
end

排序方法。

  def sort_column
    Vacation.column_names.include?(params[:sort]) ? params[:sort] : 'start_at'
  end

  def sort_direction
    %w(asc desc).include?(params[:direction]) ? params[:direction] : 'asc'
  end

更新:

Vacation.joins(:person).column_names

返回:

=> ["id", "start_at", "end_at", "free", "reason", "person_id", "accepted"]

如果您遵循RailsCast的指南,则应该有如下代码:

@vocations = Vocation.order(params[:sort] + ' ' + params[:direction])

并且,如果您想按其他模型(在您的情况下为Person模型)中的列进行排序,则必须更新查询以加入people表以使其起作用。

@vocations = Vocation.includes(:person).order(params[:sort] + ' ' + params[:direction]).references(:people)

在您看来,

= sortable "people.first_name", "Employee"

更新:

您可以更新sort_column来处理联接表的特殊情况:

  JOINED_TABLE_COLUMNS = %w(people.first_name)
  def sort_column
    if JOINED_TABLE_COLUMNS.include?(params[:sort]) || Vacation.column_names.include?(params[:sort])
      params[:sort]
    else
      'start_at
    end
  end

我认为您应该可以通过以下方式解决此问题:

 = sortable "persons.first_name", "Employee"

暂无
暂无

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

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