Search code examples
ruby-on-railsrubyruby-on-rails-4cancan

Rails - Restrict users from following themselves


I have a following system and I would like to restrict the users controller action 'follow' if the params[:id] is the same as the current user.

I use cancancan (an up to date cancan gem) to do my authorizations work.

controllers/users_controller.rb

def follow
  Followership.create(leader_id: params[:id], follower_id: current_user.id)
  ...
end

models/user.rb

class User < ActiveRecord::Base
  has_many :followers, :class_name => 'Followership', dependent: :destroy
  has_many :followed_by, :class_name => 'Followership', dependent: :destroy
  ...
end

models/followership.rb

class Followership < ActiveRecord::Base
  belongs_to :leader, :class_name => 'User'
  belongs_to :follower, :class_name => 'User'
  ...
end

Solution

  • Add a validation on your Followship model:

    class Followership < ActiveRecord::Base
      belongs_to :leader, :class_name => 'User'
      belongs_to :follower, :class_name => 'User'
    
      validate :doesnt_follow_self
    
      private
    
      def doesnt_follow_self
        errors.add(:base, 'You can\'t follow yourself') if leader == follower
      end
    end