Ruby on rails 3.1 对一种mime格式而不是另一种格式进行分页的Rails控制器的最佳实践

Ruby on rails 3.1 对一种mime格式而不是另一种格式进行分页的Rails控制器的最佳实践,ruby-on-rails-3.1,will-paginate,Ruby On Rails 3.1,Will Paginate,我的rails项目正在对HTML格式进行分页,而不是对其他格式进行分页。有人能提出一种更优雅的方法来处理@contacts集合中的差异吗?也许分页版本应该是一个只支持HTML的不同方法 def index if request.format.to_sym == :html @contacts = Contact.paginate(page: params[:page]).search(params[:search]) else @contacts = Contact.se

我的rails项目正在对HTML格式进行分页,而不是对其他格式进行分页。有人能提出一种更优雅的方法来处理@contacts集合中的差异吗?也许分页版本应该是一个只支持HTML的不同方法

def index
  if request.format.to_sym == :html
    @contacts = Contact.paginate(page: params[:page]).search(params[:search])
  else
    @contacts = Contact.search(params[:search])
  end      

  respond_to do |format|
    format.html { render html: @contacts }
    format.mobile { render mobile: @contacts }
    format.json { render json: @contacts }
    format.xml { render xml: @contacts.to_xml }
  end
end
我的解决方案是将paginate作为RESTful资源添加到routes.rb中,它自动为我提供了route helper方法:paginate_contacts_path

resources :contacts do
  collection do
    get 'paginate'
  end
end
并在ContactsController中使用单独的分页方法

def index
  @contacts = Contact.search(params[:search])

  respond_to do |format|
    format.html { render html: @contacts }
    format.mobile { render mobile: @contacts }
    format.json { render json: @contacts }
    format.xml { render xml: @contacts.to_xml }
  end
end

def paginate
  @contacts = Contact.paginate(page: params[:page]).search(params[:search])

  respond_to do |format|
    format.html
  end
end

强烈建议使用单独的方法,因为这样会产生不一致性,并使工件不易测试。例如,在文档中,您还需要创建异常

另一种方法是使用一些参数来处理这个问题。现在它突然(当您只更改视图时)返回不同的数据。对于未知的开发人员来说,这可能看起来是一个错误,并且可能会引发问题


因此,不要神奇地执行此操作,清除参数或分离方法。

使用will paginate gem会神奇地自动添加分页参数,但我认为您是在建议(我同意)应该有一个def paginate方法,我可以1)在任何地方显式引用而不是contacts_path,或者2)将contacts_path重定向到contacts控制器::paginate。如果我选择了#2,我应该怎么做呢?很明显我应该选择#2,我通过在我的RESTful资源(如上所示)中添加“paginate”来做到这一点,很好!是的,我想你知道我是怎么想的。这实际上是为了让现在和将来都必须参与项目的开发人员清楚。祝你的项目好运!