Search code examples
elixirphoenix-frameworkecto

Ecto association to more than one schemas


Assuming

schema "infrastructure_instances" do
  belongs_to :provider, MyApp.Infrastructure.Provider
  belongs_to :user, MyApp.Web.User
end

and

schema "infrastructure_providers" do
  belongs_to :user, MyApp.Web.User
  has_many :instances, MyApp.Infrastructure.Instance
end

... and

schema "account_users" do
  has_many :providers, MyApp.Infrastructure.Provider
  has_many :instances, MyApp.Infrastructure.Instance
end

How would i build an association for an Instance to a Provider and a User

This works, but there should certainly be a better way,

def create_instance(attrs \\ %{},user) do
  user
  |> build_assoc(:instances,provider_id: provider_id)

Thank You


Solution

  • build_assoc(user, :instances, provider: provider)
    

    (hopefully it works this way) or

    build_assoc(user, :instances, provider_id: provider_id)
    

    seems fine to me. So your way is not that bad I think.

    Or maybe this if you need to create a changeset ->

    %Instance{}
    |> Changeset.change()
    |> Changeset.put_assoc(:user, user_struct_or_changeset)
    |> Changeset.put_assoc(:provider, provider_struct_or_changeset)