I'm a newbie to Ecto. I have three tables defined in Ecto schema called User, Role and UserRole. In UserRole i need to update additional field (such as "status") on associating both the User and Role table, Which will make an entry in UserRole table.
// User Schema
schema "users" do
field :first_name, :string
field :last_name, :string
field :email, :string
many_to_many :roles, Role, join_through: "userroles"
end
// Role Schema
schema "roles" do
field :code, :string
field :description, :string
many_to_many :users, User, join_through: "userroles"
end
// UserRole Schema
schema "userroles" do
field :is_default, :boolean, default: false
field :status, :string
field :user_id, :id
field :role_id, :id
belongs_to :users, User, define_field: false
belongs_to :roles, Role, define_field: false
end
// The below are the steps i have done
- Opened iex using iex -S mix
Inserted a record in User table.
a. userChangeset = User.changeset(%User{}, %{email: "[email protected]", first_name: "xyz", last_name: "z"}) b. user1 = Repo.insert!(userChangeset)
Inserted a record in Role table.
a. roleChangeset = Role.changeset(%Role{}, %{code: "CON", description: "Consumer"}) b. role1 = Repo.insert!(roleChangeset)
- Now all fine, I have user record at variable user1 and role record at variable role1 respectively.
- Now i need to associate both the records to insert a record at UserRole Table. Which will be created automatically on associating the user1 and role1 record
Associating both the user1 and role1 record by using the below command at iex
a. userRoleAssoc = user1 |> Repo.preload(:roles) |> Ecto.Changeset.change() |> Ecto.Changeset.put_assoc(:roles, [role1]) |> Repo.update!
- But the problem here is, I need to insert the status field to while associating. How do I do that.
I tried updating the UserRole record
a. fetchUserRole = Repo.get_by(UserRole, id: 1)
b. fetchUserRole = %{ fetchUserRole | status: "Active"}
c. fetchUserRole |> Ecto.Changeset.change() |> Repo.update
It had given the following result. In the result it got updated but not reflected in my DB. The result stays as like the above image.
{:ok, %UserRole{ meta: #Ecto.Schema.Metadata<:loaded, "userroles">, companies: #Ecto.Association.NotLoaded, id: 1, is_default: false, role_id: 1, roles: #Ecto.Association.NotLoaded, status: "Active", user_id: 1, users: #Ecto.Association.NotLoaded }}
My question here is, Is there any way to insert the field value while associating if it is a many_to_many association. If yes means, How to do that.
status: "Active"
in #10? And if you got something back in #10 it should be reflected in the database.Repo.get_by
should return identical values to your priorRepo.update
. Confused how to help... – Lanny Bosechange/2
above: hexdocs.pm/ecto/Ecto.Changeset.html#change/2 – Lanny BoseEcto.Changeset.change(fetchUserRole, %{status: "Active"})
– Lanny Bose