I have a problem with ExMachina, where I have company <-> role_relation <-> user
many_to_many relationsship between users and companies.
the role relation table has a NOT NULL
constraint on the key role_name
, company_id
and user_id
, the only columns other than timestamps.
I have factories like this
def supplier_company_factory do
%Company{
name: sequence(:name, &"Company-#{&1}"),
contact_name: sequence(:contact_name, &"test-#{&1}"),
users:
build_pair(:user,
roles: [build(:role_relation, role_name: "supplier")]
)
}
end
def user_factory do
%User{
email: sequence(:email, &"USER-#{&1}@EXAMPLE.COM"),
first_name: sequence(:first_name, &"test-#{&1}"),
last_name: sequence(:first_name, &"user-#{&1}"),
office_phone: "office phone",
mobile_phone: "mobile phone",
details: %{
settings: %{use_local_timezone: true}
}
}
end
def role_relation_factory do
%RoleRelation{
role_name: "auction_manager"
}
end
if i then write insert(:supplier_company)
I get this error:
** (Postgrex.Error) ERROR 23502 (not_null_violation) null value in column "company_id" of relation "role_relations" violates not-null constraint
table: role_relations
column: company_id
Failing row contains (supplier, 1, null, 2025-02-26 08:50:42, 2025-02-26 08:50:42).
You can clearly see in the insert query, that the company_id
is NULL
.
Extra info
role_relation schema
@primary_key false
schema "role_relations" do
field(:role_name, :string)
belongs_to(:user, User, primary_key: true)
belongs_to(:company, Company, primary_key: true)
timestamps()
end
company schema
schema "companies" do
[fields ...]
many_to_many(
:users,
User,
join_through: RoleRelation,
join_keys: [company_id: :id, user_id: :id],
on_replace: :delete,
on_delete: :delete_all
)
end
user schema
schema "users" do
[fields...]
many_to_many(
:companies,
Company,
join_through: RoleRelation,
join_keys: [user_id: :id, company_id: :id],
on_replace: :delete,
on_delete: :delete_all
)
end
Am I missing something here?