Question

I am running the Kaminari gem for my pagination.

Controller

def dashboard
  @projects = Project.find_by_user_id(current_user)
  if @projects.size > 10
    @projects.page(params[:page]).per(10)
  end
end

Dashboard view

= paginate @projects, :theme => 'twitter-bootstrap-3', :remote => true

In my case, the @projects is sometimes only 1 record or even zero records. When it is nil, I get an error on the params[:page] being nil.

So this works

def dashboard
  @projects = Project.page(params[:page]).per(10)
end

This gets error undefined method 'page' for #<Project:0x007f8cac5f14b0>

  def dashboard
    @projects = Project.find_by_user_id(current_user).page(params[:page]).per(10)
  end

I think it is because the @projects is only a couple of records which is less than the 10 specified in .per

I tried adding a @projects.count or @projects.size but I get the error undefined method 'size' for #<Project:0x007f8c996865f0>

def dashboard
  @projects = Project.find_by_user_id(current_user)
  if @projects.size > 10
    @projects.page(params[:page]).per(10)
  end
end

What the hell am I doing wrong!? haha

I am guessing I can fix this in the first instance instead of trying to fix the second or third options. Any help would be greatly appreciated.

Was it helpful?

Solution

The issue is Project.find_by_user_id(current_user) returns an Array, not an ActiveRecord::Relation

You should do something like:

current_user.projects.page(params[:page]).per(10)

If your relationships are correctly setup.

Or:

Project.where(user_id: current_user.id).page(params[:page]).per(10)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top