ruby-on-rails - 允许在 Rails 中向某些用户上传更大的文件大小
问题描述
我正在使用 Carrierwave 音频上传音频文件。到目前为止,我已经为所有用户设置了一定的大小,但我只是实现了高级订阅。我想有一种方法让订阅用户上传更大的文件。由于您无法访问模型中的 current_user,我该怎么做?
require 'elasticsearch/model'
class Track < ApplicationRecord
include Taggable
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
belongs_to :user, counter_cache: true
belongs_to :album, optional: true, counter_cache: true
belongs_to :pseudonym, optional: true
has_many :favorites, counter_cache: true
has_many :comments, as: :commentable
has_many :events, as: :eventable, dependent: :delete_all
has_many :flags, as: :flaggable, dependent: :delete_all
has_many :listings
enum explicit: { standard: 0, explicit: 1 }
mount_uploader :image, ImageUploader
mount_uploader :audio, AudioUploader
validates :audio, file_size: { less_than: 15.megabytes }, presence: true
validates :image, file_size: { less_than: 1.megabytes }, presence: true
validates :tag_list, presence: true
attr_accessor :crop_x, :crop_y, :crop_w, :crop_h
after_update :crop_image
def crop_image
image.recreate_versions! if crop_x.present?
end
def self.tagged_with(name)
Tag.find_by_name!(name).tracks
end
end
解决方案
既然Track
属于User
,你可以在这里做的是这样的事情。
class Track < ApplicationRecord
# other code
belongs_to :user, counter_cache: true
mount_uploader :audio, AudioUploader
validates :audio, file_size: { less_than: audio_file_size_limit }, presence: true
private
def audio_file_size_limit
return 15.megabytes unless user.premium_subscriber?
30.megabytes
end
# other code
end
推荐阅读
- javascript - JWT 子声明在验证期间被忽略
- javascript - 这些 Jquery 示例之间有什么区别?
- netsuite - 如何在 SuiteScript 2 Suitelet 中将 NetSuite 文件作为字节数组获取?
- matlab - 求解复合线性优化问题
- r - 在 group_walk() 中调用多个函数
- c# - 数据表服务器端处理排序功能只工作一次
- c# - 从发布堆栈跟踪中定位异常
- java - 如何验证 json 到 BigDecimal 的位数,但只是小数位数?
- awk - 如何翻转字符串的最后一个字符
- html - 如何使用 Windows Powershell 在网页中访问基于 javascript 的对话框窗口?