gpt4 book ai didi

ruby-on-rails - 列出与模型间接相关的 ActiveStorage 附件

转载 作者:行者123 更新时间:2023-12-04 06:20:57 25 4
gpt4 key购买 nike

我是 Rails 的新手,正在尝试了解 ActiveStorage 的工作原理。

该应用程序具有以下模型:

class Client < ApplicationRecord
has_many :jobs
has_many :messages
end
class Job < ApplicationRecord
belongs_to :client
has_many_attached :images
end
class Message < ApplicationRecord
belongs_to :client
has_many_attached :images
end

在数据库中,我可以看到多态关系,我也可以理解什么 SQL 查询会得到我想要的结果。

但是我想知道是否有一种惯用且有效的方法来检索与客户端相关的所有附件?

最佳答案

查询与给定记录关联的附件

您可以直接使用 ActiveStorage::Attachment 查询附件类(class)。 record属性是连接到附加类的多态关联。

这是一个例子

ActiveStorage::Attachment.where(record: Job.first)

查询与一组记录关联的附件

您还可以将一组记录传递给 record选项
ActiveStorage::Attachment.where(record: Job.all)

查询与多组记录关联的附件

您可以使用 or 查找与多组记录关联的附件。
ActiveStorage::Attachment.where(record: Job.all).or(ActiveStorage::Attachment.where(record: Message.all))

把它放在一起...

查找与给定记录关联的多组记录关联的所有附件
client = Client.first
ActiveStorage::Attachment.where(record: client.jobs).or(ActiveStorage::Attachment.where(record: client.messages))

它不漂亮,但很有效。所有查询都是通过 Active Record 完成的,这意味着它发生在单个 SQL 语句中,不需要将任何对象加载到内存中。

关于ruby-on-rails - 列出与模型间接相关的 ActiveStorage 附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52258583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com