如何在多对多关系中使用联接 table 中的字段?

How to work with fields from a join table in many-to-many relationships?

我有通常的多对多关系:

class Post < ApplicationRecord
  has_many :posts_and_images
  has_many :images, through: :posts_and_images
end

class PostsAndImage < ApplicationRecord
  belongs_to :post
  belongs_to :image
end

class Image < ApplicationRecord
  has_many :posts_and_images
  has_many :posts, through: :posts_and_images
end

我在 posts_and_images table 中添加了一个字段。现在我不明白我怎么能在这个领域工作。

例如,我在posts_and_imagestable中添加了一个description字段。也就是说,这个字段对每个post.

的每张图片都有唯一的描述

我想像这样处理这个领域:

- @post.images.each do |image|
  / ...
  = content_tag :div, image.description

请告诉我,我怎样才能达到这个结果?

您想首先根据约定命名连接模型。 PostsAndImage 各方面都很奇怪。

class Post < ApplicationRecord
  has_many :post_images
  has_many :images, through: :post_images
end

class PostImage < ApplicationRecord
  belongs_to :post
  belongs_to :image
end

class Image < ApplicationRecord
  has_many :post_images
  has_many :posts, through: :post_images
end

但您可能会想出更好的名称,例如附件、媒体等。

您不想遍历 images,而是想遍历 post_images:

- @post.post_images.each do |post_image|
  = content_tag :div, post_image.description
  # you can get the image with post_image.image