2015-06-01 109 views
23

在Rails混合範圍和關聯,如果我有以下設置:在鳳凰城/外生

class Post < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :post 

    def self.approved 
    where(approved: true) 
    end 
end 

然後,我可以做這樣的事情:

post = Post.find(100) 
comments = post.comments.approved 

,迅速得到所有已批准的評論對於給定的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 

我已經得到了postcomments預加載:

post = MyApp.Post 
     |> MyApp.Repo.get(100) 
     |> MyApp.Repo.preload(:comments) 

我甚至不知道從哪裏在MyApp.Comment開始與approved範圍。

+3

本博客文章可能指向你在正確的方向:http://blog.drewolson.org/composable-queries-ecto/ – Gazler

回答

3

我不認爲這是可能的當前版本的Ecto。預加載不允許進行過濾。另一種方法是通過查詢獲得註釋:

(from comment in MyApp.Comment, 
    where: comment.post_id == ^post_id 
    and comment.approved == true, 
select: comment) |> Repo.all 
9

預加載允許接​​收查詢。所以你可以像這樣過濾相關的評論。

post = 
    MyApp.Post 
    |> Ecto.Query.preload(comments: ^MyApp.Comment.approved(MyApp.Comment)) 
    |> MyApp.Repo.get(100) 

而在你Comment模型

def approved(query) do 
    from c in query, 
    where: c.approved == true 
end