使用Rails 4.2.7,Pundit,Mongoid和RailsAdmin的未定义方法`to_criteria'

时间:2016-08-17 23:23:42

标签: ruby-on-rails ruby-on-rails-4 rails-admin pundit mongoid5

我有一个带有rails_admin(0.8.1),pundit(1.1.0)和mongoid(5.1.4)的Rails 4.2.7应用程序

我创建了Campaign scaffold,并在CampaignController中将authorize @campaign添加到set_campaign。当我浏览http://localhost:3000/campaigns/57b34dd3f5740c23d3066e43时,我得到unable to find policy CampaignPolicy for <Campaign _id ...

我运行rails g pundit:policy campaign来创建CampaignPolicy,现在显示行动有效。但是当我浏览到RailsAdmin http://localhost:3000/admin/campaign时,我得到了:

undefined method `to_criteria' for Campaign:Class
lib/mongoid/criteria.rb merge! method

我通过修改CampaignPollicy中的Scope来“解决”它,但我想知道是否有更好的解决方案

class CampaignPolicy < ApplicationPolicy
  def show?
    true
  end
  class Scope
    attr_reader :user, :scope
        def initialize(user, scope)
      @user = user
      @scope = scope
    end
    def resolve
    end
  end
end

1 个答案:

答案 0 :(得分:0)

好的,想通了,我以为我会分享答案。

class CampaignPolicy < ApplicationPolicy
  ...
  class Scope
    def resolve
      if @user.admin?
        scope.all  # this prevents undefined method `to_criteria'
      else
        scope.where(...) # put some biz logic here
      end
    end
  end
end