Rails 5.2 Active Storage 添加自定义属性 [英] Rails 5.2 Active Storage add custom attributes
问题描述
我有一个带附件的模型:
I have a model with attachments:
class Project < ApplicationRecord
has_many_attached :images
end
当我附加并保存图像时,我还想保存附加的图像的附加自定义属性 - display_order
(整数).我想用它对附加的图像进行排序,并按照我在此自定义属性中指定的顺序显示它们.我已经查看了 #attach
方法以及 ActiveStorage::Blob
模型的 ActiveStorage 源代码,但似乎没有内置方法来传递一些自定义元数据.
When I attach and save the image I also want to save an additional custom attribute - display_order
(integer) with the attached image. I want to use it to sort the attached images and display them in the order I specified in this custom attribute. I've reviewed ActiveStorage source code for #attach
method as well as ActiveStorage::Blob
model but it looks like there is no built in method to pass some custom metadata.
我想知道,用 ActiveStorage 解决这个问题的惯用方法是什么?过去,我通常只向表示我的附件的 ActiveRecord 模型添加一个 display_order
属性,然后简单地将它与 .order(display_order: :asc)
查询一起使用.
I wonder, what's the idiomatic way to solve this problem with ActiveStorage? In the past I would usually just add a display_order
attribute to the ActiveRecord model which represents my attachment and then simply use it with .order(display_order: :asc)
query.
推荐答案
如果您需要为每个图像存储额外的数据并根据该数据执行查询,我建议提取一个 Image
模型包装附加的file
:
If you need to store additional data with each image and perform queries based on that data, I’d recommend extracting an Image
model that wraps an attached file
:
# app/models/project.rb
class Project < ApplicationRecord
has_many :images, dependent: :destroy
end
# app/models/image.rb
class Image < ApplicationRecord
belongs_to :project
has_one_attached :file
delegate_missing_to :file
scope :positioned, -> { order(position: :asc) }
end
<%# app/views/projects/show.html.erb %>
<% @project.images.positioned.each do |image| %>
<%= image_tag image %>
<% end %>
请注意,上面的示例视图会导致对具有 N 个图像的项目进行 2N+1 次查询(对项目图像进行一次查询,对每个图像的 ActiveStorage::Attachment
记录进行一次查询,对每个附加 ActiveStorage::Blob
).为了清楚起见,我特意避免优化查询数量.
Note that the example view above causes 2N+1 queries for a project with N images (one query for the project’s images, another for each image’s ActiveStorage::Attachment
record, and one more for each attached ActiveStorage::Blob
). I deliberately avoided optimizing the number of queries for clarity’s sake.
这篇关于Rails 5.2 Active Storage 添加自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!