↓ Ir para o conteúdo principal

← todas as notas

📎 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, and comment_likes tables.
  • comment_likes uses comment_id and user_id as primary keys and also has a unique index on that pair.
  • User defines many_to_many :liked_comments, Comment, join_through: CommentLike, on_replace: :delete.
  • Comment defines many_to_many :liked_by, User, join_through: CommentLike, on_replace: :delete.
  • Post belongs to a user and has many comments.
  • The join schema CommentLike is defined with @primary_key false and belongs_to fields for user and comment.
  • The like action preloads liked_comments, changes the user struct, and uses put_assoc with the target comment.
  • The comment list query joins posts, comments, comment likes, and users to produce comment plus is_liked.
  • The post suggests iex -S mix for learning and debugging Ecto models.