Rails中的update.js需要第二次提交

时间:2015-08-19 13:31:36

标签: javascript ruby-on-rails ruby ajax forms

我在Rails中遇到一个小问题(非常小)。

远程:真正的更新表单(调用update.js.erb)需要两个提交而不是一个正确刷新视图。

def update
@user = User.find(params[:id])
if @user.update_attributes(update_user_params)
  respond_to do |format|
    format.html {
      flash[:success] = "Votre profil a été mis à jour."
      redirect_to @user
    }
    format.js
  end
else
  render 'edit'
end

以下是观看代码(我正在使用方法:&#39; put&#39;因为我从主页调用它,而不是edit.html,但即使没有它,问题仍然存在):< / p>

<%= form_for @user, html: { multipart: true }, remote: true, method: 'put' do |f| %>
  <%= f.label :location, 'Ville', class: 'popover-title' %>
  <%= f.select :location, cities_options %>
  <%= f.submit "Valider", class: 'btn-addon' %>
<% end %>

这是我在提交时看到的内容:

Started PUT "/users/101" for 127.0.0.1 at 2015-08-19 15:25:05 +0200
Processing by UsersController#update as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"hZMd5usgyZVgY4DxqNp0PxF8JPvRk/V+WAGTjFLhj8rqS0y1UCbzbQ9e7HYH20oNdn3TK6FXrLgeDXYnrZeVIg==", "user"=>{"location"=>"Paris"}, "commit"=>"Valider", "id"=>"101"}
User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 101]]
User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 101]]
CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "101"]]
(0.0ms)  begin transaction
User Exists (0.1ms)  SELECT  1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('andrey.soloviev.s@gmail.com') AND "users"."id" != 101) LIMIT 1
SQL (0.3ms)  UPDATE "users" SET "location" = ?, "lat" = ?, "lng" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["location", "Paris"], ["lat", 48.856614], ["lng", 2.3522219], ["updated_at", "2015-08-19 13:25:05.511789"], ["id", 101]]
(2.2ms)  commit transaction
Rendered users/update.js.erb (0.1ms)
Completed 200 OK in 208ms (Views: 4.6ms | ActiveRecord: 2.9ms)

最后,这是update.js.erb:

$('.location-name').html('<%= current_user.location %>');

基本的Rails js,没什么特别的。上面的代码告诉我,一切似乎都正常工作。但是,在提交时,update.js使用数据库中的旧值刷新位置(在新数据库之前)。只有在第二次提交时,我才会看到正确的值出现。

如果有人有任何想法或解决方案,我将永远感激。

提前谢谢大家!

1 个答案:

答案 0 :(得分:2)

我认为current_user是控制器上的辅助方法,我想这是缓存的。将其切换到您更新的用户对象。 $('.location-name').html('<%= @user.location %>');