Elixir Ecto: Multiple belongs_to relationship in a schema
Asked Answered
A

1

7

I have the following schema.

defmodule Message do
  use Ecto.Schema

  schema "messages" do
    belongs_to :user, FPL.Club, foreign_key: :user_to_id
    belongs_to :user, FPL.Club, foreign_key: :user_from_id
  end
end

As you can see, I have two belongs_to relationships I'd like to define here, corresponding to user who sent the message, and the user to whom this message is sent. In the message table, I have two fields named user_to_id and user_from_id.

But this fails with the following error:

== Compilation error on file lib/message.ex ==
** (ArgumentError) field/association :user is already set on schema
    lib/ecto/schema.ex:1697: Ecto.Schema.put_struct_field/3
    lib/ecto/schema.ex:1677: Ecto.Schema.association/5
    lib/ecto/schema.ex:1512: Ecto.Schema.__belongs_to__/4
    lib/message.ex:12: (module)
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

What am I doing wrong?

Anschluss answered 5/5, 2017 at 19:47 Comment(0)
H
11

You need to use different names for the relationships:

belongs_to :user_to, FPL.Club, foreign_key: :user_to_id
belongs_to :user_from, FPL.Club, foreign_key: :user_from_id

The name specified here is the field in the struct where Ecto will load the referenced record, which needs to be unique.

Heti answered 5/5, 2017 at 19:49 Comment(2)
That works. How do I then use the has_many relationship on the User schema? Is has_many :messages, FPL.Message correct?Anschluss
Try this: has_many :messages_to, FPL.Message, foreign_key: :user_to_id (and then to -> from).Heti

© 2022 - 2024 — McMap. All rights reserved.