I have a users table and a countries table as follow:
field :name, :string
field :code, :string
has_many :users, MyApp.Accounts.User
end
field :password_hash, :string
field :email, :string
field :password, :string, virtual: true
field :password_confirmation, :string, virtual: true
field :first_name, :string
field :last_name, :string
field :gender, :string
(…)
belongs_to :country, MyApp.Country, on_replace: :nilify
timestamps()
end
A country has_many users and user belongs to country. I want to add country_id to user as an update action. My changeset:
country = attrs["country"]
user
|> cast(attrs, [:first_name, :last_name, :gender, :birth_date, :country_id])
|> put_assoc(:country, country)
|> assoc_constraint(:country)
I can update first_name, last_name, gender etc but Country is not being associated with my user. Nothing happens and it remains nil:
Hestia.Accounts.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
country: #Ecto.Association.NotLoaded<association :country is not loaded>,
country_id: nil,
email: "rodrigo@example.com",
first_name: "Rod",
gender: "male",
(…)
updated_at: ~N[2019-12-28 17:33:43.813377]
}
It’s the first time I am trying to use associations in Phoenix. What am I doing wrong?
Thanks