我正在使用载波宝石来上传图像
我的用户视图中有此表单,其中提供了文件(图像)的上传按钮
<%= form_for(@user, html: { multipart: true }) do |f| %>
Update your profile pic:
<span class="avatar">
<%= f.file_field :avatar %>
</span>
<%= f.submit "Update", class: "btn btn-primary" %>
<% end %>
这是我的用户控制器
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:avatar)
end
end
当我从浏览器中单击表单上的提交按钮时,我收到了这个http请求。
Started PATCH "/users/1" for 127.0.0.1 at 2018-07-05 13:15:39 +0100
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"VXaEvnTD7nl+2d/0n1+iB/zwRX+Mf3nbMt0/Qr7m/nYpTmyXCxih981pIbGKGT9qdSfB7zyB6l
CKGdA9uiLouw==", "user"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x00007fbf2a794af0 @tempfile=#<Tempfile:/var/folders
/42/plkmf9zn755b0lvwc2_5k30c0000gn/T/RackMultipart20180705-37847-7s1tba.png>, @original_filename="Screen Shot 2018-07-03 at 1
0.23.17.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"Screen S
hot 2018-07-03 at 10.23.17.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Update", "id"=>"1"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], [
"LIMIT", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
No template found for UsersController#update, rendering head :no_content
Completed 204 No Content in 161ms (ActiveRecord: 0.6ms)
但是数据库中没有任何更新(即当前用户的avatar属性的值仍为nil)。我也看不到图像已保存在任何地方。
答案 0 :(得分:1)
这是您的控制器update
方法不完整,例如:
def update
user = User.find(params[:id]) # Set user
if user.update(user_params) # Save to database
# Success, redirect to show/index/whatever
else
# Fail, render form again
end
end
我建议您阅读以下内容:http://guides.rubyonrails.org/action_controller_overview.html