choise
choise

Reputation: 25244

only allow specific users to access model

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!

Upvotes: 0

Views: 193

Answers (1)

toddsundsted
toddsundsted

Reputation: 6345

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 model1 and model2 to company and user in your queries. From your description, model1 and model2 have a company_id column, and company has a user_id column. Depending on how you have the associations in your models set up, you could do something like:

Model1.joins(:company => :user).where(:users => {:id => 1})

or (assuming an appropriate authentication framework):

Model1.joins(:company => :user).where(:users => {:id => current_user.id})

Upvotes: 1

Related Questions