2016-05-10 23 views
0

UserUserからConnectionモデルに続くことができるTwitterのようなアプリケーションでは、Follower@userに戻ってきた場合に表示するのに問題があります。has_many関連の要素が別の要素に含まれているかどうかを調べるにはどうすればよいですか?

ウェブ/モデル/ user.ex

defmodule MyApp.User do 
    use MyApp.Web, :model 

    schema "users" do 
    field :last_name, :string 

    has_many :follower_connections, MyApp.Connection, foreign_key: :followee_id 
    has_many :followers, through: [:follower_connections, :follower] 

    has_many :followee_connections, MyApp.Connection, foreign_key: :follower_id 
    has_many :followees, through: [:followee_connections, :followee] 
[...] 

ウェブ/モデル/ connection.ex

defmodule MyApp.Connection do 
    use MyApp.Web, :model 

    schema "connections" do 
    belongs_to :follower, MyApp.User 
    belongs_to :followee, MyApp.User 
[...] 

ウェブ/コントローラ/ user_controller.ex

[...] 
def show(conn, %{"id" => id}) do 
    user = 
    Repo.get!(User, id) 
    |> Repo.preload([:followers, :followees, 
        :followee_connections, 
        :follower_connections]) 
    conn 
    |> assign(:user, user) 
    |> render("show.html") 
end 
[...] 

ウェブ/テンプレート/ユーザー/ show.html.eex

<ul> 
<%= for connection <- @user.follower_connections do %> 
    <li> 
     <%= connection.follower.last_name %> 
     <%= if connection.followee.???include?(????) do %> 
     (You follow him/her back.) 
     <% end %> 
    </li> 
<% end %> 
</ul> 

connection.followerがの一部または@user.followeesに含まれている場合はどのように見つけることができますか?

ボーナス質問:これはEctoの文書のどこにありますか?

答えて

1

私はこの仕事ができると思う:

<%= if Enum.any?(@user.followee_connections, fn(x) -> x.followee_id == connection.follower_id end) do %> 
    (You follow him/her back.) 
<% end %> 

それはあなたが始めることができ、より良い方法はおそらくあります。

また、フォロワーと接続をすべて事前にロードすると、人が数万人のフォロワーを持つ場合など、多くのRAMを消費する可能性があると私は考えます。私はそれを制限付きのクエリーに書き直すのは理にかなっていると思うので、毎回50人のフォロワーしかロードしません。

関連する問題