Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 775
Joseph Smitty Avatar asked Dec 09 '15 16:12

Joseph Smitty


1 Answers

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

like image 114
Gazler Avatar answered Nov 05 '22 14:11

Gazler