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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With