Currently I've defined two models, Accounts and Users, within my app using has_and_belongs_to_many associations.
An account within the app refers to an organization such as a company.
I'm able to get the current user easily, but I'm struggling to find a way to build an object to store the current account if the current user has multiple accounts.
Right now I'm defaulting to the first account that belongs to the current user and I'm guessing the solution is going to be along the lines of including the selected account id parameter in my defined routes, but I'm not really sure how to do that since I'm fairly new to RoR and would prefer to set it up behind the scenes if possible without revealing the account id within the URL.
Edit - Adding Code
models/account.rb
class Account < ActiveRecord::Base
#define relationship to users
has_and_belongs_to_many :users
#...
end
models/user.rb
class User < ActiveRecord::Base
#define relationship to account
has_and_belongs_to_many :accounts
#...
end
** Previous 'current_account' implementation before updating accounts and users associations to habtm.
controller/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_account
private
def current_account
if user_signed_in?
@current_account ||= Account.find(current_user.account_id)
end
end
end
The current_account helper method above no longer works because I've changed my associations from Account has many Users and Users belong to Account TO Accounts has and belongs to many Users and vice versa. For now I've updated the above code to
@current_account ||= current_user.accounts[0]
but obviously that remains as a static variable where I need it to be dynamic depending on which account the user selects.
Also I'm using devise, so I'm able to utilize their current_user helper method to easily get the current user.
Any help would be greatly appreciated!