开发者

refactoring will_paginate attributes in a controller query

Hey. I am using the following line开发者_运维技巧 over and over in my controller index queries. Does it makes sense to create a new application method to re-use it? Any suggestions on how I could extract this and perhaps pass the :per_page attribute a variable parameter?

paginate :page => params[:page], :per_page => 12

Thanks for your time!


You could definitely do this in your application controller. I think since it's a one-liner, you're saving very little in terms of keystrokes and text. Still, if you wanted to do it, you could put something like this in application_controller.rb file

# optional-- this lets you use the method in views as well
helper_method :paginate_helper

...
# optional, but safer
protected

def paginate_helper(obj_to_paginate, page_limit)
  obj_to_paginate.paginate :page => params[:page], :per_page => page_limit
end

depending on the scope that you'll use this helper in, you may want to add an if statement regarding params[:page]. paginate will work with :page=> nil, however you could get an error for params[] if params doesn't exist (i.e. you'd be doing nil[], trying to treat nil like an array).


Like it says in the will_paginate README...

You can define it like this:

class Post < ActiveRecord::Base
  cattr_reader :per_page
  @@per_page = 50
end

... or like this:

class Post < ActiveRecord::Base
  def self.per_page
    50
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜