ruby 尝试用户订购参数时出现“堆栈级别太深错误”

ruby `stack level too deep error` when trying to user order param

我正在尝试将 sort_by 参数添加到使用 Kaminari 进行分页的 rails 应用程序。将参数添加到查询时,出现堆栈级别太深的错误。

app/controllers/file_items_controller.rb

class FileItemsController < AccountsController
  def index
    account = Account.includes(:credentials).find params[:account_id]
    @page = page_param.to_i
    @tab = 'Files'
    @credential = if params[:credential_id].blank?
                    account.credentials.first || nil
                  else
                    account.credentials.find(params[:credential_id])
                  end
    return unless  @credential
    file_items = FileItem.file_item_list(@credential.root_folder, sort_by)
    @total_count = file_items.count
    @max_per_page = file_items.count <= 15 ? 'all' : max_per_page.to_i
    file_items_scope = Kaminari.paginate_array(file_items.select(&:file?), total_count: file_items.count).page(page_param)
    @file_items = if max_per_page == 'all'
                    file_items_scope.per(file_items.count) || []
                  else
                    file_items_scope.per(max_per_page) || []
                  end
  end

  private

  def page_param
    params[:page] || 1
  end

  def max_per_page
    val = params[:per] || 15
    val.to_i < 15 ? 15 : val unless val == 'all'
  end

  def sort_by
    params[sort_by] || 'created_at'
  end
end

app/models/file_item.rb

def file_item_list(folder, sort = :name)
  folder.children(sort).map do |file_item|
    if file_item.file_item_type == 'file'
      file_item
    else
      file_item_list file_item
    end
  end.flatten
end
...
def children(sort = :name)
  return [] unless directory?
  credential.file_items.where(path: full_path).order(sort)
end
...

你有params[sort_by],你真正想要的是params[:sort_by]。您的方法正在尝试评估 sort_by 并进入无限循环。