0

I'm using Rails 3.2 and Kaminari for pagination. I'm using the same controller action (index) for rendering all articles and all articles of a specific user. My controller code looks like this:

  def index
    @articles = (params[:mine] == "true") ? current_user.articles : Article.search(params[:search], :page => params[:page])

    respond_to do |format|
      format.html
      format.json { render json: @articles }
    end
  end

and in my Article model:

  def self.search(search, opts)
    if search.present?
      where("category LIKE ? OR article_type LIKE ?", "%#{search}%","%#{search}%").page(opts[:page]).per(25)
    else
      page(opts[:page]).per(25)
    end
  end

My problem is I do not know how to apply sorting and pagination when showing the current_user's articles. The code for sorting is not yet there by the way. With the current code, I'm having this error 'undefined method `current_page' for #Article' when accessing the index action with the mine parameter set to true.

So my question is how do you apply sorting and pagination when using current_user.articles? Sample code would really help. Thanks a lot!

gerky
  • 6,267
  • 11
  • 55
  • 82

1 Answers1

1

I guess you should replace your class method with a scope:

scope :search, lambda {|search, opts|
  if search.present?
    where("category LIKE ? OR article_type LIKE ?", "%#{search}%","%#{search}%").page(opts[:page]).per(25)
  else
    page(opts[:page]).per(25)
  end
}

Then:

source    = (params[:mine] == "true") ? current_user.articles : Article
@articles = source.search(params[:search], :page => params[:page])
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • thanks, but I have a question though, why scopes? Aren't they the same as class methods? – gerky Aug 27 '12 at 09:45
  • `scopes` are chainable, not class methods – apneadiving Aug 27 '12 at 09:48
  • Oh..I see. But I'm still a bit confused, how can you call the search method on an array of article objects (current_user.articles)? Sorry if it's a newbie question. – gerky Aug 27 '12 at 09:54
  • Look in console it's not an array it's an active record query or alike – apneadiving Aug 27 '12 at 10:35
  • Yup, I've checked current_user.articles.class and it really returns an array. But it works though, which is weird. – gerky Aug 27 '12 at 11:28
  • Apparently, class methods in Rails 3 no longer execute queries as long as an active record relation is returned, based on this http://stackoverflow.com/questions/5899765/activerecord-rails-3-scope-vs-class-method. – gerky Aug 27 '12 at 11:35