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?
One more question (please let me know if I should start another OP): if I create the “likes” entity with just a migration and a schema, I am able to seed it with something like this:
If I remember correctly, the changeset function that phx.gen.json creates does not have casts for entity_id. Check to see if your Like.changeset/2 casts :post_id and :user_id.
If that doesn’t work, we can try something else.