我正在从paperclip迁移到Rails 5.2和活动存储。我使用rails作为API。
如何获取has_many_attached:images的URL路径
这是有效的单个文件的代码:
class UserSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes %i[email name username]
....
attribute :verification_url do
if object.verification_file.attachment
URI.join(ActionController::Base.asset_host, rails_blob_path(object.verification_file))
end
end
....
end
当我尝试为多图像做类似的事情时,我只是获取这些图像,而不是他们的URL。
include Rails.application.routes.url_helpers
attributes :id, :name, :description, :images
def images
if object.images.attachments
object.images.each do |image|
URI.join(ActionController::Base.asset_host, rails_blob_path(image))
end
end
end
这是解决方案:
def images
return unless object.images.attachments
image_urls = object.images.map do |image|
URI.join(
ActionController::Base.asset_host,
rails_blob_path(image))
end
image_urls
end