Simon
Simon

Reputation: 762

Rails Models - before_read or similar that allows you to run an method before accessing the data

So I am implementing cancancan into all my models so that both reads and access to each attribute in a model must be authorised

for write operations I can use before_save and before_create but I need something that works for reading data.

My plan is to write some code in ApplicationRecord that would then work for all models with the goal to prevent user from accessing any data they don't have specific privileges for.

While I know there are solutions at the controller level I need the extra security at the model level

Upvotes: 1

Views: 350

Answers (1)

Hiren Bhalani
Hiren Bhalani

Reputation: 848

There are callbacks for after_find and after_initialize, but if you want to have it before executing the select query, here is something you can try.

There are few methods being used in the ActiveRecord gem, you just need to override those and have your verification done using cancancan gem.

Here is the pseudo code of what I'm trying to suggest here. Let me know if you need exact code that fix the issue.

class ApplicationRecord
  class << self
    %i[find_with_ids where find_take_with_limit find_nth find_nth_with_limit].each do |attribute|
      define_method :"#{attribute}" do
        super if can_access?
      end
    end

    def can_access?
      can :read, self
    end
  end
end

Upvotes: 1

Related Questions