Search code examples
ruby-on-railsrubykaminariruby-2.2rails-4-2-1

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


I'm trying to add a sort_by params to a rails app that uses Kaminari for paging. When add the param to the query I get a stack level too deep error.

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
...

Solution

  • You have params[sort_by], what you actually want is params[:sort_by]. Your method is trying to evaluate sort_by and going into an infinite loop.