Rails Pagination with Kaminari with has_many :thro

2019-08-05 03:19发布

问题:

I have three relevant models. A User which has_many :photos and belongs_to :dorm, a Dorm which has_many :users and has_many :photos, :through => :users, and a Photo class which belongs_to :users and belongs_to :dorm.

I want to paginate all the photos that are in a dorm with kaminari. I have it in my Gemfile and ran the bundle command.

In my dorms_controller:

@dorm=Dorm.find(params[:id])
@photos=@dorm.photos.page(params[:page]).per(3)

and in my Dorm show view (actually in a partial, _index.html.erm rendered in the show view):

<%= paginate @photos %>

This gives me the error: undefined method 'page' for #<Class:0x107483d68>.

I know why this doesn't work (shouldn't be called on a class), but I don't know how to make it work...

回答1:

hrm, strange. That should work. I actually made a vanilla app with an action you shown above and the following models, but I couldn't reproduce the error.

class Dorm < ActiveRecord::Base
  has_many :users
  has_many :photos, :through => :users
end

class User < ActiveRecord::Base
  belongs_to :dorm
  has_many :photos
end

class Photo < ActiveRecord::Base
  belongs_to :user
end

There should be another root cause in your app code. So, could you track down the problem a bit more? To begin with, does the following code work in your rails console?

@dorm.photos.page(1)


回答2:

  1. is gem 'kaminari' in your Gemfile ?
  2. run bundler after changing your Gemfile