2015-06-01 19 views
23

Trong Rails, nếu tôi có các thiết lập sau:Trộn Phạm vi và hiệp hội ở Phoenix/Ecto

class Post < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :post 

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

Sau đó, tôi có thể làm một cái gì đó như thế này:

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

để nhanh chóng có được tất cả các ý kiến ​​đã được phê duyệt cho số Post đã cho.

Tôi có thể làm điều gì đó tương tự trong 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 

tôi đã có post với comments được nạp sẵn:

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

Tôi thậm chí không chắc chắn bắt đầu từ đâu với phạm vi approved trong MyApp.Comment.

+3

bài viết trên blog này có thể chỉ cho bạn đi đúng hướng: http://blog.drewolson.org/composable-queries-ecto/ – Gazler

Trả lời

3

Tôi không nghĩ rằng có thể với phiên bản Ecto hiện tại. Tải trước không cho phép lọc. Thay thế là để có được những ý kiến ​​với một truy vấn:

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

tải trước được phép nhận các truy vấn. Vì vậy, bạn có thể lọc các nhận xét được liên kết như thế này.

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

Và trong mô hình Comment bạn

def approved(query) do 
    from c in query, 
    where: c.approved == true 
end 
Các vấn đề liên quan