Get the association with Ecto
In the schema of my post model I have this line:
belongs_to :developer
So a post is associated with a developer. When I have a post
struct and try to access the developer I might see this:
> Tilex.Repo.get(Tilex.Post, 42).developer
#Ecto.Association.NotLoaded<association :developer is not loaded>
Getting the developer is now a two step process:
- Construct a query based on the association
- Use that query to acquire the struct
To construct a query based on the association we can use the Ecto.assoc/2
function:
query = Ecto.assoc(post, :developer)
Then this query is executed with the Repo.one
function:
developer = Tilex.Repo.one(query)
There ya go!
Tweet