Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir Ecto: Multiple belongs_to relationship in a schema

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?

like image 999
Saket Mehta Avatar asked May 05 '17 19:05

Saket Mehta


1 Answers

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.

like image 173
Dogbert Avatar answered Oct 06 '22 20:10

Dogbert