如何在Rails 7中配置Action Text仅允许图片类附件?
解决Action Text仅允许图片附件的配置问题
你遇到的错误是因为has_rich_text方法并不支持:attachments这个关键字参数,直接传入会触发参数未知的报错。以下是两种可行的实现方式:
方式一:在模型中添加自定义验证
通过验证RichText字段关联的附件类型,确保只有图片能被保存:
class YourModel < ApplicationRecord has_rich_text :content # 验证content字段的附件仅为图片 validate :content_attachments_are_images private def content_attachments_are_images return if content.blank? content.attachments.each do |attachment| allowed_types = %w[image/png image/jpeg image/gif image/jpg] unless attachment.content_type.in?(allowed_types) errors.add(:content, "仅支持上传PNG、JPG、GIF格式的图片") end end end end
方式二:限制Active Storage附件类型(全局/模型级)
如果希望所有Action Text的附件都仅允许图片,可以在ActiveStorage::Attachment模型中添加验证,但这种方式会影响所有使用Active Storage的附件:
# 在config/initializers/active_storage.rb中添加 ActiveStorage::Attachment.class_eval do validate :image_content_type private def image_content_type allowed_types = %w[image/png image/jpeg image/gif image/jpg] unless content_type.in?(allowed_types) errors.add(:file, "仅支持上传PNG、JPG、GIF格式的图片") end end end
补充:前端辅助限制
为提升用户体验,可以在Trix编辑器中隐藏非图片的上传入口(比如通过CSS或JS隐藏文件类型选择的非图片选项),但后端验证始终是必须的,防止绕过前端限制的恶意上传。
内容的提问来源于stack exchange,提问作者Slaknation
相关产品推荐
相关产品推荐

