通过has_many与Kaminari进行Rails分页:通过关系 [英] Rails Pagination with Kaminari with has_many :through Relationship

查看:83
本文介绍了通过has_many与Kaminari进行Rails分页:通过关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个相关模型. has_many :photosbelongs_to :dorm的用户,has_many :usershas_many :photos, :through => :users的宿舍,以及belongs_to :usersbelongs_to :dorm的照片类.

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.

我想用kaminari对宿舍中的所有照片进行分页.我将其保存在我的Gemfile中,并运行了bundle命令.

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.

在我的dorms_controller中:

In my dorms_controller:

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

并在我的宿舍显示视图中(实际上是在显示视图中呈现的部分_index.html.erm中):

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

<%= paginate @photos %>

这给了我错误: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...

推荐答案

hrm,很奇怪.那应该工作.实际上,我使用上面显示的动作和以下模型制作了一个香草应用程序,但无法重现该错误.

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

您的应用代码中应该还有另一个根本原因.因此,您能否进一步解决问题?首先,以下代码在您的Rails控制台中是否可以工作?

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)

这篇关于通过has_many与Kaminari进行Rails分页:通过关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆