# Restricting visibility of data based on user id

**URL:** <https://discuss.rubyonrails.org/t/restricting-visibility-of-data-based-on-user-id/6249>\
**Category:** rubyonrails-talk\
**Created:** [December 23, 2006, 6:41am UTC](https://discuss.rubyonrails.org/t/restricting-visibility-of-data-based-on-user-id/6249 "2006-12-23T06:41:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Timothy\_Jones](https://avatars.discourse-cdn.com/v4/letter/t/a3d4f5/32.png) [@Timothy\_Jones](https://discuss.rubyonrails.org/u/Timothy_Jones)\
**Post date:** [December 23, 2006, 6:41am UTC](https://discuss.rubyonrails.org/t/restricting-visibility-of-data-based-on-user-id/6249/1 "2006-12-23T06:41:01Z")

</div>

I'm building a Rails app to manage an investment portfolio, with models including: &nbsp;&nbsp;User (has\_many :portfolios) &nbsp;&nbsp;Portfolio (belongs\_to :user, has\_many :accounts) &nbsp;&nbsp;Account (belongs\_to :portfolio)

The relevant SQL is: &nbsp;&nbsp;CREATE TABLE users &nbsp;&nbsp;( &nbsp;&nbsp;id INTEGER AUTO\_INCREMENT PRIMARY KEY, &nbsp;&nbsp;... &nbsp;&nbsp;); &nbsp;&nbsp;CREATE TABLE portfolios &nbsp;&nbsp;( &nbsp;&nbsp;id INTEGER AUTO\_INCREMENT PRIMARY KEY, &nbsp;&nbsp;user\_id INTEGER NOT NULL, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... &nbsp;&nbsp;); &nbsp;&nbsp;CREATE TABLE accounts &nbsp;&nbsp;( &nbsp;&nbsp;id INTEGER AUTO\_INCREMENT PRIMARY KEY, &nbsp;&nbsp;portfolio\_id INTEGER NOT NULL, &nbsp;&nbsp;&nbsp;);

The app requires user authentication, and I wish to limit visibility of data to that associated with the logged in user (i.e., the portfolio list should only include the current user's portfolios, not all portfolios in the database).

My current approach is to add :conditions and :joins to the find() methods in the controllers. For example, the portfolio controller's edit() method includes: &nbsp;&nbsp;@portfolio = Portfolio.find(params[:id], :conditions =\> ["user\_id = ?", session[:user\_id]]) (straightforward since there's a direct link between the portfolio record and the user record)

and the account controller's edit method includes: &nbsp;&nbsp;&nbsp;&nbsp;@account = Account.find(params[:id], :joins =\> ["inner join portfolios as p on accounts.portfolio\_id = p.id and p.user\_id = " + session[:user\_id].to\_s]) (have to join through the portfolio record to get to the user)

This seems error prone (have to remember to do this throughout the controllers), particularly as you get farther down into the model (e.g., accounts include transactions, which will require two joins to reach the user\_id).

Is there a more systematic/declarative way to go about this? I've looked through the main list of Rails plugins, but all the ACL ones seem to be limited to roles, and not data ownership.

TIA, Tim
