Answer the question
In order to leave comments, you need to log in
How to check the size, type, and number of attached files on the server side using Rails Action Text?
In general, I can not find a way to check the attached files. I use Action Text, it includes Trix editor and Active Storage for saving files.
class Post < ApplicationRecord
has_rich_text :content
validates :content, presence: true
validate :content_length
validate :content_embeds
def content_embeds
if content.embeds.any?
errors.add(:content, 'Нельзя загружать более 4 изображений') if content.embeds.size > 4
content.embeds.each do |attach|
errors.add(:content, 'Изображение не может весить > 10 мБ') if attach.byte_size > 1242880
errors.add(:content, 'Можно загружать только изображения') unless attach.image?
errors.add(:content, 'Недопустимый формат изображения') unless attach.content_type == 'image/jpeg' || attach.content_type == 'image/png'
end
end
end
def content_length
max_length = 50
symbol_size = 0
if content.embeds.any?
content.embeds.each do |attach|
symbol_size += (attach.filename.size + 2)
end
end
errors.add(:content, 'Слишком длинный текст') if (content.to_plain_text.size - symbol_size) > max_length
content.embeds.each { |attach| puts "ATTACH #{attach}"}
end
Answer the question
In order to leave comments, you need to log in
In general, I dug a little into the sources, everything was simple: it
rich_text_content.body.attachments
returns the attached files when creating the model, well, then do what you like with it)
Link to the rails sources
Maybe not in essence, but in embeds, in my opinion, not only images can be attached, but also other formats, no?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question