How to preload association by default on user login

I have a simple app which has users table with role_id and a related table roles with role ids and names.
I am using Phauxth for authentication and authorization and I have certain controllers/routes which are only allowed for certain roles.

My question is, what is the best way to load the association and where to load it to make it available to conn.assigns.current_user?

My issue is that the roles association is not loaded by default (and I am not sure where and how to load it when the user login) and every time I need to check if a user has the role to do something or anytime I need to display a user’s role, I am calling a helper function which basically does Repo.preload user, :role
When I login, the conn.assigns has a current_user, but that user doesn’t have the role association loaded.
Any suggestions?

In a plug, probably.

I am doing something like this (preloading) in the account context, but I don’t really like it.

def list_users do
|> Repo.preload(:role)

def get(id), do: Repo.get(User, id) |> Repo.preload(:role)

I would like to be able to preload it when the user is logged in and not worry about it later.
I have the following plugs in the browser pipeline, @idi527, do you mean writing a new plug or doing the preload in some of these?

pipeline :browser do
plug :accepts, [“html”]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
plug Phauxth.Authenticate
plug Phauxth.Remember

I don’t know why you don’t like it, that’s exactly how you should be doing it.

I would probably rename the functions to get_with_roles and list_with_roles to make it fully explicit about my intent though.


@dimitarvp Thanks for the answer.
I thought, there must be a better way to do this, hence the topic.
Good suggestion about the function names, I’ll do that, thanks.

I’d write a new one, and make it clear by its name that it’s for preloading user roles.

1 Like