Problem with build_assoc

i have this models phone.ex and tenant.ex which have an association of belongs_to and has_many respectively. The phone.ex model has one field which is :mobile_number of type :integer. The idea is a tenant can have more than one :mobile_number so in my TenantController for the :create action i have the following code

def create(conn, %{"tenant" => tenant_params}) do

changeset = conn.assigns.current_user
|> build_assoc(:tenants, :phone)
|> Tenant.changeset(tenant_params)

case Repo.insert(changeset) do
{:ok, tenant} ->
conn
|> put_flash(:info, "Tenant created successfully.")
|> redirect(to: tenant_path(conn, :show, tenant))
{:error, changeset} ->
render(conn, "new.html", changeset: changeset)
end
end

I also put the :mobile_number field in the new.html.eex for Tenant template folder so that if given it is populated in the phones table

I get an error which says schema ZitoApp.User does not have association [:tenants, :phone] what could be wrong as per the explanations i have given above? Thank you

1 Like

build_assoc/3 takes the association as the second argument. Since you are using the pipe, the first argument to your function is the user, Tenant, struct. You are passing the second argument as :tenants, and the third argument as :phone. The second argument should be :phones if the Tenant struct has_many :phones.

|> build_assoc(:phones)

It looks like you are trying to create a Tenant, so I’m not sure build_assoc is what you want here. You also need make sure you are setting up your form as a nested form.

I recommend reading Nested Forms in Phoenix and Working with Ecto associations and embeds for examples of how to set up a form with associations.

Edit: I assumed a user is a tenant, but in the controller you are creating a new tenant from current_user, so I’m not sure what the relationship is between a user and a tenant.

3 Likes

Thanks so much, this is exactly what i was looking for

1 Like