In Rails, if I have the following setup:
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
def self.approved
where(approved: true)
end
end
Then I can do something like this:
post = Post.find(100)
comments = post.comments.approved
to quickly get all the approved comments for the given Post
.
How can I do something similar in Ecto?
defmodule MyApp.Post do
use Ecto.Model
schema "posts" do
#columns omitted
has_many :comments, MyApp.Comment
end
end
defmodule MyApp.Comment do
use Ecto.Model
schema "comments" do
#columns omitted
belongs_to :post, MyApp.Post
end
end
I've got the post
with comments
pre-loaded:
post = MyApp.Post
|> MyApp.Repo.get(100)
|> MyApp.Repo.preload(:comments)
I am not even sure where to start with the approved
scope in MyApp.Comment
.