The tuple in ecto has_many

Hi all

Could someone please tell me, for what does the tuple in the middle of has_many means?

 schema "posts" do
    has_many :comments, {"posts_comments", Comment}, foreign_key: :assoc_id
  end 

In a normal scenario, I would only pass a module with implemented schema.

Thanks

1 Like

The first element of the tuple is actually the table you want to load the Comment from. This is very useful when you don’t have a single concrete table, such as “comments”, but many tables for each relationship you have comments for in your system. Such as “posts_comments”, “tags_comments”, “chapters_comments”, etc. It is a mechanism for doing polymorphic associations but without shoving all of your data in a single place.

5 Likes

What does the second parameter mean?

The second parameter is the schema! You can consider this:

schema "posts" do
  has_many :comments, Comment, foreign_key: :assoc_id
end

to be the same as

schema "posts" do
  has_many :comments, {"comments", Comment}, foreign_key: :assoc_id
end

assuming you have define schema "comments" in your Comment schema.

6 Likes

Thanks jose for help.

And 1000 thanks, that you created elixir for us.