Search code examples
ruby-on-railsscopeaccountuser-accounts

How to always set a value for account-scope in Rails?


I'm working on a multi-user, multi-account App where 1 account can have n users. It is very important that every user can only access info from its account. My approach is to add an account_id to every model in the DB and than add a filter in every controller to only select objects with the current account_id. I will use the authorization plugin.

Is this approach a good idea?

What is the best way to always set the account_id for every object that is created without writing

object.account = @current_account

in every CREATE action? Maybe a filter?

Also I'm not sure about the best way to implement the filter for the select options. I need something like a general condition: No matter what else appears in the SQL statement, there is always a "WHERE account_id = XY".

Thanks for your help!


Solution

  • This is similar to a User.has_many :emails scenario. You don't want the user to see other peoples emails by changing the ID in the URL, so you do this:

    @emails = current_user.emails
    

    In your case, you can probably do something like this:

    class ApplicationController < ActionController::Base
      def current_account
        @current_account ||= current_user && current_user.account
      end
    end
    
    # In an imagined ProjectsController
    @projects = current_account.projects
    @project = current_account.projects.find(params[:id])