In-Context Associations

How are people using associations in their context functions, say create and update. Are you adding an argument or what? I’m talking in-context here, not associations in other contexts

For example, say I want to create a Post that belongs to an Organization, and they’re both in the same context. Post belongs_to Organization, and Organization has_many posts. The associations are pretty boilerplate, but what is a mystery to me is how to write the function that creates a Post that belongs to a given Organization. Previous to contexts, I made a changeset in the controller where authorization and lookup is happening based on the logged in user. When creating the changeset, I started with a Post that already had organization_id set.

It seems like something similar could be accomplished by adding another function that took an organization argument, but I wanted to see what others are doing.

The simple way to approach it is: Leave web-specific code in the controller, lift everything else into the context module.

That leaves the controller with the responsibility of pulling values out of conn.assigns and conn.params and passing whatever is relevant into the context.

Context can then validate and perform the action, returning either {:ok, result} or {:error, changeset}, leaving it to the controller to convert the result into a HTTP response, localizing the error message with GetText if required.

3 Likes