【发布时间】:2020-05-07 16:39:58
【问题描述】:
我有一个模型Profile,它有一个附件image。
class Profile < ApplicationRecord
belongs_to :user, dependent: :destroy
has_one_attached :image
validates :image,
content_type: [:gif, :png, :jpg, :jpeg],
size: { less_than: 2.megabytes , message: 'must be less than 2MB in size' }
after_initialize :set_default_image
has_many :gallery_items, dependent: :destroy
accepts_nested_attributes_for :gallery_items, allow_destroy: true
validates :name, :short_description, :slug, presence: true
#...
除了图像验证(我使用的是active storage validation gem)之外,Profile 还会验证name、short_description 和slug 的存在。
自从实现了这个,我有了一个新的需求。我现在想允许用户将图像与其他属性分开提交。
我不想更改底层模型。因此,我想引入一个单独的控制器和类来处理一个单独提交图像的表单。
我尝试了两种方法。
首先,我有一个简单的类来处理这个问题:
class ProfileImageFormSubmission
def initialize(record, params)
@params = params
@record = record
end
def save
record.update_attribute(:image, image_param)
end
private
attr_accessor :params, :record
def image_param
params.fetch(record_param).require(:image)
end
def record_param
record.class.name.underscore.to_sym
end
end
它会像这样在我的控制器中调用:
class ProfileImagesController < ApplicationController
before_action :require_login
def update
@profile = Profile.find_by(user_id: current_user.id)
if ProfileImageFormSubmission.new(@profile, params).save
#...
问题是,图像未经过验证,因此无论如何都会附加到配置文件中。 (我使用 #update_attribute 是因为我想跳过对其他属性的验证——当字段没有呈现给用户时,显示 name 列的错误是没有意义的。)
我还尝试通过在模型之外运行验证来解决问题。但在这里,我很难理解如何将 ActiveStorage 与一个普通的旧 Ruby 对象集成。
class ProfileImageFormSubmission
include ActiveModel::Model
include ActiveStorage
include ActiveStorageValidations
attr_accessor :record, :params
has_one_attached :image
validates :image,
content_type: [:gif, :png, :jpg, :jpeg],
size: { less_than: 2.megabytes , message: 'must be less than 2MB in size' }
def initialize(record, params)
@params = params
@record = record
end
def save
binding.pry
record.update_attribute(:image, image_param)
if record.invalid?
record.restore_attributes
return false
end
end
# This model is not backed by a table
def persisted?
false
end
private
def image_param
params.fetch(record_name).require(:image)
end
def object_name
record.class.name.underscore.to_sym
end
end
我什至无法实例化上述类,因为它失败并出现以下错误:
NoMethodError (undefined method `has_one_attached' for ProfileImageFormSubmission:Class):
单独验证活动存储项目的最佳方法是什么?
是否可以在单个列上运行验证而不会触发其他验证错误?
是否可以在ApplicationRecord 模型之外使用活动存储项?
【问题讨论】:
标签: ruby-on-rails rails-activestorage ruby-on-rails-6