Hello,
it is frustrating. Excuse me, but I try to implement a many-to-many Relation without a result. What I want is: I have Users and I have groups. Between Users and Groups exists a m:n-Relation. So I implement:
A Group:
defmodule Lmsphx.Accounts.Group do
use Ecto.Schema
import Ecto.Changeset
import Ecto.Query
alias Lmsphx.Accounts
schema "group" do
field :title, :string
#has_many :user, Accounts.User
many_to_many(:user, Accounts.User, join_through: Lmsphx.Accounts.UserGroup)
timestamps()
end
@doc false
def changeset(group, attrs) do
group
|> cast(attrs, [:title])
|> validate_required([:title])
end
def get_groups(nil), do: []
def get_groups(ids) do
Repo.all(from a in Accounts.Group, where: a.id in ^ids)
end
end
A User:
defmodule Lmsphx.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
schema "user" do
field :email, :string
field :firstname, :string
field :gebdate, :date
field :lastname, :string
field :login, :string
field :password, :string
many_to_many(:group, Accounts.Group, join_through: Lmsphx.Accounts.UserGroup)
timestamps()
end
@doc false
def changeset(user, attrs) do
IO.write("Get user data ...")
user
|> cast(attrs, [:lastname, :firstname, :login, :password, :email, :gebdate])
|> validate_required([:lastname, :firstname, :login, :password, :email, :gebdate])
|> cast_assoc(:group, required: true)
end
end
And an UserGroup:
defmodule Lmsphx.Accounts.UserGroup do
use Ecto.Schema
alias Lmsphx.Accounts
import Ecto.Changeset
@primary_key false
schema "user_group" do
belongs_to :user, Accounts.User
belongs_to :group, Accounts.Group
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:user_id, :group_id])
|> validate_required([:user_id, :group_id])
end
end
In a LiveView I want to generate Checkboxes, so I can put a User to different groups. I wrote a multiselect_checkboxes-Function, which I want to use in this liveview. But If I call this function with:
multiselect_checkboxes(
f,
:group_collection,
Enum.map(@group_collection, fn a -> { a.title, a.id } end),
selected: Enum.map(@changeset.data.group,&(&1.id))
)
I got the error: ** protocol Enumerable not implemented for #Ecto.Association.NotLoaded of type Ecto.Association.NotLoaded (a struct)**
It makes sense, BUT!, where I have to implement the preload?
regards,
Sven