so first my model structure:
company has many users, user belongs to company
model1 belongs to company, company has many model1
model2 belongs to company, company has many model2
for the index action of model1 i simply do something like
@model1 = current_user.company.model1s # i use devise for auth
in my controller i put first
before_filter :authenticate_user!
the problem is, the show action (of course) shows every logged in user every record of model one.
what is the best option to restrict model1 and model2 records only to users that belong to the company the model1 and model2 are belonging to?
thanks!
In the general case, use a plugin or gem like (in no particular order) CanCan, Clearance or one of the others here. For what it’s worth, I’ve used acl9 successfully in the past.
Most of these solutions implement authorization control at the controller/view level, and control access to specific instances of models (AKA rows in the database) that way.
Also see this question, which covers the topic from the perspective of which is best.
Finally, if you want to roll your own, the simplest solution is to join from
model1andmodel2tocompanyanduserin your queries. From your description,model1andmodel2have acompany_idcolumn, andcompanyhas auser_idcolumn. Depending on how you have the associations in your models set up, you could do something like:or (assuming an appropriate authentication framework):