undefined方法`total_pages' - 使用load_and_authorize_resource时

时间:2015-06-06 12:14:25

标签: ruby-on-rails ruby-on-rails-4 authorization cancancan

使用cancancan进行授权。我正在使用will_paginate进行表格分页。它工作正常,直到我在控制器中添加load_and_authorize_resource。在控制器中使用load_and_authorize_resource时,will_paginate会抛出ActionView::Template::Error (undefined method total_pages'对于#)`: Abilyty.rb:

def initialize(user)    
    if user.user_type == "ADMIN" then
      can :manage, :all
      cannot :manage, ParentMessageController
    elsif user.user_type == "MANAGEMENT" then
      can :manage, :all
      cannot :manage, ParentAttendance
end

控制器:

class AssignmentsController < ApplicationController  
  before_action :set_assignment, only: [:show, :edit, :update, :destroy]
  load_and_authorize_resource
def index
 getAssignments
end

def getAssignments
@assignments = Assignment.all
if (@assignments != nil && @assignments.length > 0) then                                                           
     @assignments = @assignments.paginate(:per_page => 5, :page => params[:page])
    end
  end

查看:

<% if @assignments != nil then%>
    <%= will_paginate @assignments, :class => @paginationClass.to_s,  renderer: BootstrapPagination::Rails %>
    <%end%>

2 个答案:

答案 0 :(得分:0)

当@assignments为空时会出现此错误,因为在这种情况下,您的代码不会调用if方法。所以,你应该总是调用分页方法来避免这个问题(在你的情况下只是删除这个无用的{ "query": { "bool": { "must": [ { "match_all": {} } ], "must_not": [], "should": [] } }, "filter": { "nested": { "path": "Contacts", "query": { "query_string": { "default_field": "Contacts.ContactValue", "query": "261981255" } } } } } )。

答案 1 :(得分:0)

更改用于分页的对象名称。

def getAssignments
@assignments = Assignment.all
if (@assignments != nil && @assignments.length > 0) then                                                           
     @assignment = @assignments.paginate(:per_page => 5, :page => params[:page])
    end
  end

并在您的视图中

<% if @assignment != nil then%>
    <%= will_paginate @assignment, :class => @paginationClass.to_s,  renderer: BootstrapPagination::Rails %>
    <%end%>

这将解决您的问题