我正在开发一个使用Rails 3.2.16的应用程序,它使用Devise gem进行用户身份验证,使用CarrierWave让用户上传个人资料图片。现在我正在尝试将此图片上传到Amazon S3,但说实话,我不知道我的代码出了什么问题。我有/profile
路由指向users#show
,我有几个for_for @user来编辑用户基本信息(如姓名,电话号码等),用户密码和用户个人资料图片。我跟着this tutorial允许用户更改他的信息而不需要密码,它用于基本信息和密码,但不用于上传图片表单。这是我的代码:
在app / users /
中查看<%= form_for(@user, :html => { method: :put, multipart: true }) do |f| %>
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<% if @user.profile_picture_url.nil? %>
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=sin+imagen" alt=""/>
</div>
<% end %>
<%= f.file_field :profile_picture %>
<%= f.hidden_field :profile_picture_cache %>
</div>
</div>
<div class="margin-top-10">
<%= f.submit "Change", class: 'btn green' %>
</div>
<% end %>
应用程序/控制器/ users_controller.rb
def update
@user = current_user
successfully_updated = if needs_password?(@user, params)
@user.update_with_password(params[:user])
else
# remove the virtual current_password attribute update_without_password
# doesn't know how to ignore it
params[:user].delete(:current_password)
@user.update_without_password(params[:user])
end
respond_to do |format|
if successfully_updated
# Sign in the user bypassing validation in case his password changed
sign_in @user, :bypass => true
format.html { redirect_to profile_path, notice: 'Success' }
format.js
else
format.html { redirect_to profile_path, alert: 'Error' }
end
end
end
private
def needs_password?(user, params)
user.email != params[:user][:email] ||
params[:user][:password].present?
end
在我的设计用户模型中:mount_uploader :profile_picture, AvatarUploader
配置/初始化/ carrierwave.rb
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => 'AWS',
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],
:region => 'us-west-2',
:endpoint => 'prestadiario.s3-website-us-east-1.amazonaws.com'
}
config.fog_directory = 'prestadiario'
config.fog_public = false
config.fog_attributes = {'Cache-Control'=>'max-age=315576000'}
end
任何帮助都将非常感激。 提前谢谢。
答案 0 :(得分:0)
好吧,我不知道为什么,但我需要添加current_password字段才能保存图片。