Search code examples
ruby-on-railsrolify

Rolify undefined method `add_role' for #<User:0x00000109c39880> in Rails 4


Just trying to install Rolify to make an admin role which has permissions to edit some concrete attributes...

I followed it's documentation step by step, everything looks fine except when I try to add a role to a user, it will say

undefined method add_role for <User:0x00000109c39880>

In my User model, I have the rolify method which should give the add_role method...

2 IMPORTANT NOTES:

Im using friendly_id Im using devise gem

Anyone can help?

User model

class User < ActiveRecord::Base
  rolify
  attr_accessor :tos_agreement
  is_impressionable :counter_cache => true, :column_name => :impressions_counter, :unique => :request_hash
  has_many :photos
  has_many :tags, through: :photos
  has_many :comments, through: :photos
  validates :tos_agreement, acceptance: true
  extend FriendlyId
  friendly_id :name, use: :slugged

  mount_uploader :avatar, AvatarUploader
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :omniauthable,
         :recoverable, :rememberable, :trackable, :validatable

  def update_with_password(params={}) 
    if params[:password].blank? 
      params.delete(:password) 
      params.delete(:password_confirmation) if params[:password_confirmation].blank? 
    end 
    update_attributes(params) 
  end

  # Omniauth Devise
  def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
    user = User.where(:provider => auth.provider, :uid => auth.uid).first
    @user = user
    if user
      return user
    else
      registered_user = User.where(:email => auth.info.email).first
      if registered_user
        return registered_user
      else
        user = User.create(name:auth.extra.raw_info.name,
          provider:auth.provider,
          uid:auth.uid,
          email:auth.info.email,
          password:Devise.friendly_token[0,20],
          )
        # if user.save
        #   UserMailer.welcome_email(@user).deliver
        # end
      end

    end
  end

end

Role.rb

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => :users_roles
  belongs_to :resource, :polymorphic => true

  scopify
end

Thanks


Solution

  • Restart your server :)

    From my personal experiences, whenever I encounter a method which should exist and does not exist, I suspect that the method which is responsible for defining the method is not being called. I would have expected rolify to generate some exception instead of failing silently.

    Rails development server will only reload your classes (what is specified in config.autoload_paths) automatically, libraries from gems will require a server restart. There are existing tools to auto reload gems.