【发布时间】:2014-07-17 02:40:09
【问题描述】:
当用户更改他们的个人资料头像(而不是重新加载页面)时,我正在尝试呈现部分内容。问题是 .js.erb 文件似乎根本没有被触发(我的控制台日志消息没有打印)。我似乎没有收到任何错误,因为它只是将页面重定向到根目录。
在我的服务器日志中(如下所示),有一个令牌真实性错误,但即使我禁用了身份验证并且错误消失了,重定向仍然发生并且 .js.erb 基本上被忽略了。
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "user"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x007f9ae101c3f8 @tempfile=#<Tempfile:/tmp/RackMultipart20140716-9847-v0ray3>, @original_filename="creator.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"creator.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Upload Avatar", "id"=>"2"}
Can't verify CSRF token authenticity
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY "users"."id" ASC LIMIT 1
(0.0ms) begin transaction
(0.1ms) commit transaction
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "2"]]
(0.0ms) begin transaction
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
SQL (0.1ms) UPDATE "users" SET "avatar" = ?, "updated_at" = ? WHERE "users"."id" = 2 [["avatar", "creator.jpg"], ["updated_at", Wed, 16 Jul 2014 14:41:14 UTC +00:00]]
(160.8ms) commit transaction
Redirected to http://localhost:3000/
.js.erb 文件
$(".avatar-container").html("<%= escape_javascript(render(:partial => 'profile/avatarContainer')) %>");
用户控制器
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params.require(:user).permit!)
format.js
format.html{
redirect_to root_path
}
else
format.js
format.html{redirect_to root_path}
end
end
end
部分:
-if current_user.avatar.url != "/assets/userProfile_dashboard.png"
.avatar-large
=image_tag current_user.avatar.url
= simple_form_for(current_user, html: {:multipart => true }, remote: true) do |f|
= f.file_field :avatar, style:"margin-top:-258px;", id: "profile-avatar"
= f.button :submit, "Upload Avatar", :class => "buttonRoundedCornersGreen ", style: "width:130px;margin-top:20px;", id: "avatar-submit"
-else
.no-avatar
= simple_form_for(current_user, html: {:multipart => true }, remote: true) do |f|
= f.file_field :avatar, id: "profile-avatar"
编辑: 经过大量搜索,文件上传的 multipart true 和 remote true 似乎是creating a conflict。我可以通过安装 Remotipart gem 来解决这个问题。
【问题讨论】:
-
你确定 jquery-rails 在 gemfile 中了吗?只需确保已加载 jquery-ujs 库即可。
-
是的,jquery-rails 就在里面。任何地方都需要我的 .js.erb 文件吗?
-
不,您不需要 js.erb 文件。在检查带有表单的页面的 html 时,表单是否具有 data-remote="true" 标记,例如
-
是的,它看起来像这样:
-
在您的布局文件中确定您需要 application.js 吗?如果是这样,应用程序js是否包含require jquery和require jquery_ujs
标签: ruby-on-rails partial