【问题标题】:How to correctly indicate the destruction of objects for the has_many: through association?如何正确指示has_many:通过关联销毁对象?
【发布时间】:2020-01-10 11:12:21
【问题描述】:

我总是写类似的代码:

class Post < ApplicationRecord
  has_many :posts_and_images
  has_many :images,
           through: :posts_and_images,
           dependent: :destroy do
             def <<(image)
               super(Array(image) - proxy_association.owner.images)
             end
           end
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,
           dependent: :destroy
end

我根据需要使用带有proxy_association 的代码。我认为在这种情况下它并不重要。我只是展示它,以便有一个完整的图片。

现在我决定再次研究各种人在他们的博客上展示的文档和各种示例。

所以我找到了一个类似的选项(基于我之前的代码):

class Post < ApplicationRecord
  has_many :posts_and_images,
           dependent: :destroy

  has_many :images,
           through: :posts_and_images do
             def <<(image)
               super(Array(image) - proxy_association.owner.images)
             end
           end
end

class PostsAndImage < ApplicationRecord
  belongs_to :post
  belongs_to :image
end

class Image < ApplicationRecord
  has_many :posts_and_images,
           dependent: :destroy

  has_many :posts,
           through: :posts_and_images
end

对于这两个示例,我在删除帖子或图片时运行了类似的场景。显然,当它们以相同的方式工作时。至少乍一看是这样的。

您能否向我解释一下这两个示例的细微差别?哪一个最可取?它们各自的优缺点是什么?

【问题讨论】:

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


    【解决方案1】:

    dependent destroy 被附加到哪一行是重要的:

    在第一种情况下(虽然很奇怪):

    • 将执行帖子的销毁,但“其”图像将首先自动销毁。
    • 将执行图片销毁,但“其”帖子将首先自动销毁。

    第二种情况:

    • 破坏帖子或图像将破坏它们的 post_and_image,即在它们与图像之间创建关系的模型或与 through 相关的帖子本身将不会被触及。

    我看到了巨大的差异。你看到这个了吗?在 Rails 控制台中尝试。

    示例:

    Post_A has 2 张图片:Image_A 和 Image_B

    Post_B has 2 张相同的图像,即 Image_A 和 Image_B。

    现在尝试以上两种方法,结果会很有趣。

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 1970-01-01
      • 2012-11-30
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 2015-01-10
      相关资源
      最近更新 更多