首页 > 解决方案 > 允许在 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

标签: ruby-on-rails

解决方案


既然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

推荐阅读