【发布时间】: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