In einer Twitter-ähnlichen Anwendung, in der ein User
einem anderen User
durch ein Connection
Modell folgen kann, habe ich Probleme zu zeigen, wenn ein Follower
wird von der @user
gefolgt wird.Wie finde ich heraus, ob ein Element einer has_many-Assoziation in einem anderen enthalten ist?
Web/Modelle/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]
[...]
Web/Modelle/connection.ex
defmodule MyApp.Connection do
use MyApp.Web, :model
schema "connections" do
belongs_to :follower, MyApp.User
belongs_to :followee, MyApp.User
[...]
web/Controller/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
[...]
web/templates/user/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>
Wie kann ich herausfinden, ob connection.follower
Teil oder in einem @user.followees
ist?
Bonus Frage: Wo ist das in der Ecto Dokumentation?