私は最近、この質問をしました: Javascript Form Submission ?
現在、フォームの送信後、 create.js.erbが最新のデータ (送信されたデータ) をロードしない理由を解明しようとしています。
データを再度送信すると、テーブルは最後から 2 番目のデータで更新されますが、絶対最新のデータではありません。
...どうして?
編集:
最新のコード -
カテゴリ コントローラー: クラス Admin::CategoriesController < Admin::AdminController ...
def create
@category = Admin::Category.new(params[:admin_category])
# You can't retrieve the @categories before attempting to add new one. Keep at end of create method.
@categories = Admin::Category.all
respond_to do |format|
if @category.save
save_to_history("The category \"#{@category.name}\" has been created", current_user.id)
format.json { render json: { html: render_to_string(partial: 'categories') } }
# I've tried both the above and bellow
#format.json { render json: { html: render_to_string('categories') } }
format.html { redirect_to(admin_categories_url, :notice => 'Category was successfully created.') }
format.xml { render :xml => @category, :status => :created, :location => @category }
else
format.html { render :action => "new" }
format.xml { render :xml => @category.errors, :status => :unprocessable_entity }
end
end
end
...
end
Javascript:
<script type='text/javascript'>
$(function(){
$('#new_admin_category').on('ajax:success', function(event, data, status, xhr){
$("#dashboard_categories").html(data.html);
});
});
</script>
解決した
@ PinnyM のメソッドを使用し、次のコードで create.json.erb ファイルを追加しました。
<% self.formats = ["html"] %>
{
"html":"<%= raw escape_javascript( render :partial => 'categories', :content_type => 'text/html') %>"
}
私の作成方法を次のように変更しました:
def create
@category = Admin::Category.new(params[:admin_category])
respond_to do |format|
if @category.save
# You can't retrieve the @categories before attempting to add new one. Keep after save.
@categories = Admin::Category.all
save_to_history("The category \"#{@category.name}\" has been created", current_user.id)
format.json
format.html { redirect_to(admin_categories_url, :notice => 'Category was successfully created.') }
format.xml { render :xml => @category, :status => :created, :location => @category }
else
format.html { render :action => "new" }
format.xml { render :xml => @category.errors, :status => :unprocessable_entity }
end
end
end
これが面倒な場合は、提案をしてください。