这与此问题半关联:How do I get the storage of each user account to update when a new file is uploaded - in Rails 3?
但它实际上有点不同,因为它涉及我的控制器中的特定动作。
这是控制器动作(upload_controller.rb
):
def destroy
upload = Upload.find(params[:id])
upload.destroy
respond_to do |format|
format.html { redirect_to("/") }
format.js { render :json => ['upload',params[:id]].to_json, :layout => false }
end
current_user.update_space
end
这是我的User.rb
型号:
# == Schema Information
# Schema version: 20110412170916
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# encrypted_password :string(128)
# password_salt :string(255)
# reset_password_token :string(255)
# remember_token :string(255)
# remember_created_at :datetime
# sign_in_count :integer
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# username :string(255)
# first_name :string(255)
# last_name :string(255)
# created_at :datetime
# updated_at :datetime
# invitation_token :string(60)
# invitation_sent_at :datetime
# plan_id :integer
# current_state :string(255)
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# space_used :integer default(0), not null
# failed_attempts :integer default(0)
# unlock_token :string(255)
# locked_at :datetime
# trial_end_date :date
# active_subscription :boolean
#
class User < ActiveRecord::Base
acts_as_voter
devise :database_authenticatable, :confirmable, :registerable, :timeoutable,
:recoverable, :rememberable, :trackable, :validatable, :invitable, :lockable
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :first_name, :last_name, :plan_id
has_friendly_id :username, :use_slug => true, :strip_non_ascii => true
before_save :update_space
has_many :uploads
def role_symbols
roles.map do |role|
role.name.underscore.to_sym
end
end
def update_space
total_size = 0
if self.uploads.count > 0
self.uploads.each do |upload|
total_size += upload[:image_file_size]
end
end
self.space_used = total_size
end
def space_left
(self.plan.storage * 1024 * 1024 * 1024) - self.space_used.to_f
end
end
有问题的行位于upload_controller.rb
所在的current_user.update_space
。当上传被破坏时,这不会更新当前登录的用户。
我如何实现这一目标?
答案 0 :(得分:3)
您正在尝试在控制器响应后运行代码。你想移动这一行:
current_user.update_space
高于respond_to
电话。