Rails [求助] notifications 不能用 kaminari 分页?

Sylor-huang · 2018年09月02日 · 最后由 Sylor-huang 回复于 2018年09月03日 · 1333 次阅读

我用的是:

gem 'rails', '~> 5.2'
gem 'notifications', '~> 0.6.0'
gem 'kaminari'

我的 notifications_controller.rb:

# notifications_controller.rb

module Notifications
  class NotificationsController < Notifications::ApplicationController
    def index
      @notifications = notifications.includes(:actor).order("id desc").page(params[:page])
      unread_ids = @notifications.reject(&:read?).select(&:id)
      Notification.read!(unread_ids)
      @notification_groups = @notifications.group_by { |note| note.created_at.to_date }
    end

    def clean
      notifications.delete_all
      redirect_to notifications_path
    end

    private

    def notifications
      raise "You need reqiure user login for /notifications page." unless current_user
      Notification.where(user_id: current_user.id)
    end
  end
end


# routs.tb 

mount Notifications::Engine, at: "notifications"

我的 index.html.erb:

# notifications/notifications/index.html.erb 的分页

<div class="paginationBox">
        <%= paginate @notifications,left:2,right:1,window: 1 %>
      </div>

我按照视频:https://ruby-china.org/topics/36891 做通知系统,现在别的功能都能正常实现,但是通知页面,不能分页显示。错误信息提示为:

NoMethodError - undefined method `total_pages' for #<Notification::ActiveRecord_Relation:0x00007fcfacae6dd8>:
  app/views/notifications/notifications/index.html.erb:33:in `_app_views_notifications_notifications_index_html_erb__2430601159943313679_70264929101860'

如果我修改notifications_controller.rbindex动作的 @notifications@notifications = notifications.includes(:actor).order("id desc").page(params[:page]).per(10)也是出现同样的错误。

如果我修改通知页面的:index.html.erb为:

# notifications/notifications/index.html.erb 的分页

<div class="paginationBox">
        <%= paginate @notifications.page(params[:page]).per(10),left:2,right:1,window: 1 %>
      </div>

则不会分页显示。

请问下大家,我是哪里出现了错误,该怎么调整?谢谢大家。

你的项目是不是还依赖了 will_paginate ?

如果是,你可以把 notifications 的分页方式改成 will_paginate 的方式。

@huacnlee 谢谢您的回复。我没有用过 will_paginate 呢,用的就只有Kaminari

然后,我的错误是:我通过index.html.erb中的 <%= paginate @notifications.page(params[:page]).per(10),left:2,right:1,window: 1 %> 点击@notifications 直接进入的norifications_controller.rb为: /Users/hs/.rvm/gems/ruby-2.5.0/gems/notifications-0.6.0/app/controllers/notifications/notifications_controller.rb😓

然后,我一直是在这里修改的。。。我然后在

app/controllers/notifications/notifications_controller.rb 修改 index action 为:

@notifications = notifications.includes(:actor).order("id desc").page(params[:page]). 现在可以分页正常了。

3 楼 已删除
4 楼 已删除
需要 登录 后方可回复, 如果你还没有账号请 注册新账号