📎 Webclip
Many to Many Relations in Ecto
The post walks through a many-to-many setup for comment likes in a Phoenix/Ecto blog app. It uses a comment_likes join table, adds many_to_many associations on User and Comment, and defines a schema for the join relation itself.
It also shows two practical pieces: a controller action that likes a comment through the current user’s liked_comments association, and a query that returns comments with an is_liked field for the current user. The author also recommends using iex -S mix for testing and debugging Ecto models.
Reading notes#
- The example starts from a blog app with users, posts, comments, and comment likes.
- The migrations create
users,posts,comments, andcomment_likestables. comment_likesusescomment_idanduser_idas primary keys and also has a unique index on that pair.Userdefinesmany_to_many :liked_comments, Comment, join_through: CommentLike, on_replace: :delete.Commentdefinesmany_to_many :liked_by, User, join_through: CommentLike, on_replace: :delete.Postbelongs to a user and has many comments.- The join schema
CommentLikeis defined with@primary_key falseandbelongs_tofields foruserandcomment. - The like action preloads
liked_comments, changes the user struct, and usesput_assocwith the target comment. - The comment list query joins posts, comments, comment likes, and users to produce
commentplusis_liked. - The post suggests
iex -S mixfor learning and debugging Ecto models.
