So I have users and roles tables.
user may have one role, but optional, role_id may be null
in database.
I added this to my migration:
alter table(:users) do
add :role_id, references(:users)
add :role_id, references(:roles)
end
then,
inside users
schema:
has_one(:role, Wshop.Accounts.Role)
inside roles
schema:
has_many(:users, Wshop.Accounts.User)
then I put this on user’s changeset
user
|> cast(attrs, [:name, :username, :password, :email, :password_confirmation])
|> validate_required([:name, :username, :password, :email, :password_confirmation])
|> put_assoc(:role, attrs.role)
I want to assign it, for example with this changeset:
{:ok, role} = Repo.insert %Role{name: "admin", description: "this is admin"}
%{
name: Faker.Name.name,
password: "somepassword",
password_confirmation: "somepassword",
username: Faker.Internet.user_name,
email: Faker.Internet.email(),
role: role
}
The problem is, the :role
here is not optional, you have to provide it in the changeset map.
** (KeyError) key :role not found in: %{"email" => "ahmed1993@batz.biz", "name" => "Rebecca Predovic", "password" => "somepassword", "password_confirmation" => "somepassword", "role" => nil, "username" => "kirstin_skiles"}
How could I make the role
optional? Any help would be appreciated