A
A
Andrey Baibek2020-02-02 09:13:27
Ruby on Rails
Andrey Baibek, 2020-02-02 09:13:27

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

All these methods work in the view when I view already saved files, but when creating the model, it says that content.embeds not exist , that is, the files attached to the text do not exist. On the client side, the validation is implemented in js and it works. How to be? Has anyone worked with Action Text?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Baibek, 2020-02-08
@AndreyBuyback

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

N
Nikola Okonesh, 2020-02-03
@nikolaokonesh

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 question

Ask a Question

731 491 924 answers to any question