Mark Karavan
Mark Karavan

Reputation: 2684

Multiple associations on same schemas

Using Ecto v2.2.6, phoenix 1.3

I have a scenario in which a user can create posts, and then other users can like posts. Users have a one-to-many relationship with posts via creation, and a many-to-many relationship with likes, via a linking table.

Setup:

mix phx.gen.json Account User users name:string
mix phx.gen.json Content Post posts title:string content:text user_id:references:users
mix phx.gen.json Content Like likes user_id:references:users post_id:references:posts

Schemas:

  schema "users" do
    field :name, :string

    has_many :posts, SocialNetwork.Content.Post, foreign_key: :users_id
    many_to_many :posts, SocialNetwork.Content.Post, join_through: "likes"

    timestamps()
  end

  schema "posts" do
    field :content, :string
    field :title, :string

    belongs_to :user, SocialNetwork.Accounts.User
    many_to_many :users, SocialNetwork.Accounts.User, join_through: "likes"

    timestamps()
  end

  schema "likes" do
    belongs_to :user, SocialNetwork.Accounts.User
    belongs_to :post, SocialNetwork.Content.Post

    timestamps()
  end

When I run mix phx.server, I get this error:

== Compilation error in file lib/social_network/account/user.ex ==
** (ArgumentError) field/association :posts is already set on schema

Is there a way that I can set up more than one association to the same schema, but through a different context?

Upvotes: 1

Views: 1079

Answers (1)

Dogbert
Dogbert

Reputation: 222398

Is there a way that I can set up more than one association to the same schema, but through a different context?

Yes, but you'll have to choose a different name for the two associations, like this:

has_many :posts, SocialNetwork.Content.Post, foreign_key: :users_id
many_to_many :liked_posts, SocialNetwork.Content.Post, join_through: "likes"

You shouldn't need to modify anything in Post since Post already uses different names for the two associations.

Upvotes: 3

Related Questions