views:

60

answers:

1

Ok, suppose to have this db schema (relation):

|User    | (1-->n) |Customer | (1-->n) |Car  | (1-->n) |Support    |
|--------|         |---------|         |-----|         |-----------|
|id      |         | user_id |         |Brand|         |Description|
|username|         |lastname |         |PS   |         |Cost       |
|password|         |firstname|         |seats|         |hours      |
|...     |         |..       |         |...  |         |...        |

The table User is generated by Authlogic.

I have 2 registred users, each one has his customers, etc. . With Authlogic I'm able to allow only authenticated users to reach controllers/views. That's fine, that's what Authlogic is made for.

Now I need to be sure that the user#1 will never reach informations belonging to customers of user#2.

In other words: if the user#1 goes to http://myapp.com/cars he will see the list of cars belonging to customers of user#1

if the car with the id=131 belongs to the customer of user#1, only user#1 have to be able to reach this information (http://myapp.com/car/1). If the user#2 insert in the browser the same link he doesn't have to be able to see this information.

Some people suggested me to create a relation between the user and each db table in order to check if a record is associated to the current_user.

What do you think? What is the best approach/solution?

+1  A: 

So you have 2 things:

  1. In index page of cars controller only cars which belong to the current user should be shown.
  2. You want to restrict show pages to the owner.

As for the index i suggest something like:

def index
  # find logic
  @cars = Car.find(:all,:conditions=>{:customer_id => current_user.customers.collect(&:id)})
  # whatever else
  # ...
end

And the show page:

def show
  # .....
  # after the find logic
  redirect_to :index unless current_user.customers.collect(&:id).include? @car.customer_id 
  # whatever else
  # ...
end

This approach is ok for most of the cases, however a better approach for performance is to add a user_id column to the costumers table, this is called denormalization but it's acceptable for performance wise.

khelll
Thanks khelll. Looks like the db denormalization is the way to follow. So i need to ad a 1->n relation between user and each table (in this case in car and support as well).
baijiu
Yes, you'd better do so.
khelll