How can I restrict records by user accounts as a default_scope, or better solution?

I currently have two models, “User” and “Report”. I want to find out
the
best way of restricting reports from certain user groups.

Given the following three groups…

  • General Manager
  • Store Manager
  • Employee

I would like to restrict the users from seeing certain reports.

  • General Manager can see all reports - no restrictions
  • Store Manager can see their reports and all employee reports
  • Employee can see only their own reports

I’ve currently been restricting access by basically “if” statements in
the
partials, but it seems like only a matter of time before one of these
fails
(by my own logic). So the idea came to me to try and set the
“default_scope” based on what role the user has… To my knowledge it
doesn’t work this way though. What would be the equivalent of this
though?
Or is there a better idea? Thanks!

On 9 February 2016 at 14:49, David McDonald [email protected] wrote:

General Manager can see all reports - no restrictions
Store Manager can see their reports and all employee reports
Employee can see only their own reports

I’ve currently been restricting access by basically “if” statements in the
partials, but it seems like only a matter of time before one of these fails
(by my own logic). So the idea came to me to try and set the
“default_scope” based on what role the user has… To my knowledge it
doesn’t work this way though. What would be the equivalent of this though?
Or is there a better idea? Thanks!

default_scope is a global scope. Several times I have used
default_scope thinking it is a good idea but every time I have
regretted it and had to remove it and find all the queries and put the
scope in manually. My advise is don’t use default_scope.

For your problem you could use a parametrised scope that is given a
role and returns the appropriate records. So you could say something
like
@reports = Report.by_role(current_user.role)
though having looked again I see that you also want to include the
users own reports, in which case pass the user to the scope and do all
the logic in there, so
@reports = Report.visible_to_user(current_user)
That line would probably be in the controller.

Colin