在Rails中,如果我有以下设置:
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
def self.approved
where(approved: true)
end
end
Run Code Online (Sandbox Code Playgroud)
然后我可以做这样的事情:
post = Post.find(100)
comments = post.comments.approved
Run Code Online (Sandbox Code Playgroud)
快速获得给定的所有批准的评论Post.
我怎样才能在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
Run Code Online (Sandbox Code Playgroud)
我post有comments预装的:
post = MyApp.Post
|> MyApp.Repo.get(100)
|> MyApp.Repo.preload(:comments)
Run Code Online (Sandbox Code Playgroud)
我甚至不确定从哪个approved范围开始MyApp.Comment.