Silex
Silex

Reputation: 1847

CanCan: abilities in database

I wonder what are the pros/cons of the two first code blocks at https://github.com/ryanb/cancan/wiki/Abilities-in-Database:

def initialize(user)
  can do |action, subject_class, subject|
    user.permissions.find_all_by_action(aliases_for_action(action)).any? do |permission|
      permission.subject_class == subject_class.to_s &&
      (subject.nil? || permission.subject_id.nil? || permission.subject_id == subject.id)
    end
  end
end

versus

def initialize(user)
  user.permissions.each do |permission|
    if permission.subject_id.nil?
      can permission.action.to_sym, permission.subject_class.constantize
    else
      can permission.action.to_sym, permission.subject_class.constantize, :id => permission.subject_id
    end
  end
end

Both seem fine to me... Maybe method #1 is less performant? Maybe method #2 is less flexible?

Upvotes: 2

Views: 1275

Answers (1)

Zamith
Zamith

Reputation: 23310

The first one will query the database with the parameters of the ability you're checking, it won't actually define any permissions.

The second method will go through all the permissions on the database an create a permission for each.

If going with the second method you'll probably want to make sure you only hit the DB once (probably when booting the server), so you don't have to do a table scan on each page load.

Upvotes: 1

Related Questions