[英]update.js in Rails needs second submit
我在Rails上遇到了一個很小的問題(確實很小)。
一個remote:true更新表單(調用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
結束
這是視圖代碼(我正在使用方法:'put',因為我是從主頁而不是edit.html調用它的,但是即使沒有它,問題仍然存在):
<%= 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 %>');
Basic Rails js,與眾不同。 上面的代碼告訴我,一切似乎都正常運行。 但是,在提交時,update.js使用數據庫中的舊值(在新值之前的舊值)刷新位置。 僅在第二次提交時,我才能看到正確的值出現。
如果有人有任何想法或解決方案,我將永遠感激不已。
謝謝大家!
我假設current_user
是控制器上的幫助器方法,我想它已被緩存。 將其切換到您更新的用戶對象。 $('.location-name').html('<%= @user.location %>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.