ruby-on-railsruby-on-rails-4rails-adminpunditmongoid5

Undefined method `to_criteria' with Rails 4.2.7, Pundit, Mongoid and RailsAdmin


I have a Rails 4.2.7 app with rails_admin (0.8.1), pundit (1.1.0) and mongoid (5.1.4)

I created Campaign scaffold and added authorize @campaign to set_campaign in CampaignController. when I browse to http://localhost:3000/campaigns/57b34dd3f5740c23d3066e43 I get unable to find policyCampaignPolicyfor <Campaign _id ...

I ran rails g pundit:policy campaign to create CampaignPolicy and now show action works. But when I browse to RailsAdmin http://localhost:3000/admin/campaign I get:

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

I "solved" it by modifying Scope inside CampaignPollicy like this but I am wondering if there is a better solution

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

Solution

  • OK, figured it out and thought I'd share the answer.

    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