在我的 Rails 應用程式中, User has_many_attached :resumes。我的用戶類如下所示
class User < ApplicationRecord
has_many_attached :resumes, dependent: :destroy
end
一切正常,用戶可以上傳他們的簡歷。但問題是用戶可以上傳任何擴展名的檔案。例如,用戶可以上傳影像檔案而不是檔案或 pdf 檔案作為簡歷。我想要實作的是只允許用戶上傳帶有這些擴展名的檔案.doc, .docx, .pdf, .txt and .rtf。我還想確保檔案大小不大于2mb. 我怎樣才能在 Rails 中實作這一點?我不確定如何為這兩個要求撰寫自定義驗證。
提前致謝。
uj5u.com熱心網友回復:
為此,您需要使用Active Storage Validation gem。您還可以在此處查看檔案。
TLDR 是您需要有兩個單獨的驗證,一個用于型別,另一個用于大小。
validates :resumes, attached: true, content_type: ['application/pdf', ..., '']
validates :resumes, attached: true, size: { less_than: 2.megabytes }
您還可以使用阻止不受支持的檔案型別的 UI。看看這里的find_field方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375564.html
標籤:红宝石轨道
