Morning/Evening elixir phoenix folks
I am playing with a many to many relationship in ecto. and it started to get interesting for me as a newcomer.
I have 4 tables
- Business
- User
- BusinessUser (the joint through table between business and user, just like a membership)
- Role (each user belongs to a role)
Business schema
schema "businesses" do
field :name, :string
......
many_to_many :users, TestApp.Accounts.User, join_through: TestApp.Businesses.BusinessUser
has_many :roles, TestApp.Roles.Role
......
end
BusinessUser schema
The :role
must be created along with BusinessUser.
@primary_key false
schema "business_user" do
belongs_to :business, TestApp.Businesses.Business
belongs_to :user, TestApp.Accounts.User
belongs_to :role, TestApp.Roles.Role
timestamps()
end
The problem
I am trying to create a Business. A current user must be associated and a new role must be created for the BusinessUser role
. I couldn’t figure out the way to associate the new :role
Currently
Check the comment for the
. My brain is a lil bit stucked, maybe there are other ways of achieving this.
def create_business(user, attrs \\ %{}) do
%Business{}
|> Business.changeset(attrs)
# Current user is associated fine.
|> Ecto.Changeset.put_assoc(:users, [user])
# TODO: How do we create and associate the new role?
# create everything in one go or create role first then put_assoc? but how?
|> Repo.insert()
# since this involve creating new role, do we need TRANSACTION?
end
Extra
I am new to Elixir Phoenix Ecto, trying to grasp the ecto way of doing things.