Ecto 关联到多个模式

Ecto association to more than one schemas

假设

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

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

...和

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

我将如何建立实例与提供者和用户的关联

这可行,但肯定有更好的方法,

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

谢谢

build_assoc(user, :instances, provider: provider)

(希望它能以这种方式工作)或

build_assoc(user, :instances, provider_id: provider_id)

我觉得不错。所以我觉得你的方法还不错。

或者,如果您需要创建一个变更集,也许可以这样做 ->

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