Joseph Smitty
Joseph Smitty

Reputation: 255

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

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.

Upvotes: 15

Views: 9133

Answers (1)

Gazler
Gazler

Reputation: 84140

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

Upvotes: 25

Related Questions