-1

我需要使用自己的分页代码,因为我的需求过于多样化和具体。我将此片段复制并粘贴到许多控制器操作中

per_page = params[:per_page] ? params[:per_page].to_i : 15
page_num = params[:page] ? params[:page].to_i : 1
to_skip = ( page_num - 1 ) * (per_page)
max_index = per_page * page_num

我做的越多,我就越觉得笨。我确信有办法更好地做到这一点,但我不确定如何。

奖金(我可以为此奖励赏金吗?)-> 如果需要,我希望能够在模型中使用 COMPUTED 参数

例子:

# frontend requests for items 15-30

def controller_action
  # code as above
  # Item.get (...)
end

# and in the model have access to these params
def get
  # use per_page, to_skip 
end
4

1 回答 1

1

我可能会把它ApplicationController作为请求过滤器

class ApplicationController < ActionController::Base
  protected
  def set_paging_params
    @per_page = params[:per_page] ? params[:per_page].to_i : 15
    @page_num = params[:page] ? params[:page].to_i : 1
    @to_skip = ( @page_num - 1 ) * (@per_page)
    @max_index = @per_page * @page_num
  end
end

class FooController < ApplicationController
  before_filter :set_paging_params, only: [:index]

  def index
    # do stuff with @per_page and others
  end
end

模型无法使用这些控制器实例变量,除非您显式传递它们(或在闭包中捕获它们,但我不知道您的Item.get实现是否支持这一点)。像这样的东西:

class FooController < ApplicationController
  before_filter :set_paging_params, only: [:controller_action]

  def controller_action
    Item.get(params[:id], per_page: @per_page,
      page_num: @page_num,
      to_skip: @to_skip,
      max_index: @max_index,
    )
  end
end

class Item
  def self.get iid, opts = {}
    # use opts[:per_page] here
  end
end
于 2013-01-18T06:13:40.853 回答