首页 > 解决方案 > Rails 5.2 无法使用 kaminari 和通知进行分页

问题描述

我的一些gemfiles:

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

我的routes.rb关于这样的通知:

mount Notifications::Engine, at: "notifications"

我的index.html关于这样的通知:

# notifications/notifications/index.html.erb

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

使用上述代码,我可以获得正确的通知,但我无法分页所有通知。我有这样的错误:

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'

如果我 将动作更改indexnotifications_controller.rb

@notifications = notifications.includes(:actor).order("id desc").page(params[:page]).per(10)

我得到相同的错误未定义方法total_pages....

如果我只是将通知index.html.erb更改为

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

它不显示任何错误,但kaminari不能分页所有通知。

那么,我在哪里有错误?请你帮助我好吗 ?非常感谢!

标签: notificationsruby-on-rails-5kaminari

解决方案


推荐阅读