ruby-on-railsrubycancancan

How to handle inflections with CanCanCan


I have ContactUsController and ContactUs model.
In contact_us_controller.rb

class ContactUsController < ApplicationController
  skip_before_action :authenticate_request, only: :create
  load_and_authorize_resource

  ...
end

In inflections.rb

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.uncountable 'ContactUs'
end

I am using CanCanCan to handle authorization. In ability.rb I have

class Ability
  include CanCan::Ability

  def initialize(user)
    unless user.present?
      can :create, ContactUs # guest users can create contact us
    end

    if user.admin?
      can :manage, ContactUs # only admins can do CRUD 
    end
  end
end

I get the following error

NameError (uninitialized constant ContactU Did you mean?  ContactUs):

activesupport (6.0.3.2) lib/active_support/inflector/methods.rb:282:in `const_get'
...

I don't know why CanCanCan checks ContactU instead of ContactUs! Despite having an inflection for 'ContactUs' as uncountable.


Solution

  • Solved by editing inflections.rb

    ActiveSupport::Inflector.inflections(:en) do |inflect|
      inflect.uncountable 'contact_us'
    end