How to get the "belongs_to" association with Ecto in Elixir?

Joseph Smitty picture Joseph Smitty · Dec 9, 2015 · Viewed 7.3k times · Source

I have a Post and Comment model. One post has many comments and one comment belongs to a post.

When showing an individual comment, how can I access the post that it belongs to?

i.e. in Ruby on Rails you could do:

@comment = Comment.find(params[:id])
@post = @comment.post

How could I achieve this using the Phoenix Elixir framework? I believe I have my model associations set up properly but I am confused on how to actually get this query in either the view or the controller.

Answer

Gazler picture Gazler · Dec 9, 2015

If you read the Ecto.Schema docs then you will see how to create a belongs_to/3 association.

defmodule MyApp.Comment do
  use MyApp.Model

  schema "comments" do
    belongs_to :post, MyApp.Post
  end
end

With the association set up you can use Repo.preload/2 to fetch the assocation.

Repo.preload(comment, :post).post

You can also preload in a query if you have not fetched the resource with Ecto.Query.preload/3