The Teams component gives your Rails application a system users to belong to (or own) multiple accounts. For more on the relationship between User
and Account
through AccountUser
, see the Accounts & Users documentation.
When you install the Teams component, it inserts the following into the _user_menu.html.erb
partial:
current_account
helperThe current_account
helper is inserted into the application_controller.rb
file. It returns the Account
record that the current user is currently in.
def current_account
return @current_account if defined?(@current_account)
if cookies[:current_account].present?
account = Account.find_by(slug: cookies[:current_account])
if account && account.users.include?(current_user)
return @current_account = account
end
end
# Fallback: User's most recently created account
@current_account = if current_user.present? && current_user.accounts.any?
current_user.accounts.order(created_at: :desc).first
else
return nil
end
end
When the user creates a new account, or switches to an account, a cookie is saved on the user's browser with the account's slug
. This is used to "remember" the account that the user is currently in, and returns to the next time this user logs in (on this browser).
When that cookie isn't present, current_account
falls back to the user's most recently created account.
I created Instrumental Components to make designing and building professional apps with Ruby on Rails easy, fast, and fun. I use it on all of my projects and I hope it helps you build something great.