【问题标题】:How to work with fields from a join table in many-to-many relationships?如何在多对多关系中处理连接表中的字段?
【发布时间】:2020-02-02 15:13:14
【问题描述】:

我有通常的多对多关系:

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 表中添加了一个字段。现在我无法理解如何使用这个领域。

例如,我在posts_and_images 表中添加了一个description 字段。也就是说,这个字段对每个帖子的每张图片都有一个唯一的描述。

我想像这样使用这个字段:

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

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

【问题讨论】:

  • 您的意思是连接表/连接模型? Middleware 是非常不同的东西。
  • @max 我更新了标题。这样更好吗?

标签: ruby-on-rails ruby-on-rails-5 ruby-on-rails-6


【解决方案1】:

您希望首先根据约定命名连接模型。 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 2021-01-28
    • 2020-07-06
    • 2020-10-09
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多