これが始まりです:
まず、ビューで link_to メソッドを使用してボタンを作成します。次に例を示します。
=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'
リソースの URL に「.json」を追加していることに注意してください。これは、パラメータの意味を確認するための AJAX 削除、google link_to の単なる例です。パラメーター :remote を true に設定して HTTP 要求を行う場合の概念、つまり、これはブラウザーからの AJAX 呼び出しに変換されます。
次に、ユーザーが手順 1 の link_to をクリックしたときにブラウザが行う AJAX 呼び出しの結果を処理できるように、JavaScript を記述します。詳細については、次のブログ投稿を参照してください: http://www.alfajango .com/blog/rails-3-remote-links-and-forms/
私のサイトの例:
jQuery(function($) {
// create a convenient toggleLoading function
var toggleLoading = function() { $("#loading").toggle() };
$("#pending_invitation")
.live("ajax:loading", toggleLoading)
.live("ajax:complete", toggleLoading)
.live("ajax:success", function(event, data, status, xhr) {
var response = JSON.parse(xhr.responseText)
if (response.result == "ok") {
$(this).fadeOut('fast');
}
else {
var errors = $('<div id="error_explanation"/>');
errors.append('<h2>Pending invitation action error</h2><ul><li>' + response.error + '</li></ul>');
$('#new_invitation_error').append(errors)
}
});
});
返された json を解析し、それに基づいてページの html を変更していることがわかります。この js は、ここには含まれていないトップ ビューで定義された CCS ID とクラスを使用することに注意してください。
独自のコントローラーを作成して json を吐き出したい場合は、次の例をご覧ください。
class InvitationsController < ApplicationController
respond_to :html, :json
# other methods here
# ...
def destroy
@invitation = Invitation.find(params[:id])
respond_to do |format|
if @invitation
@invitation.destroy
flash[:success] = I18n.t 'invitations.destroy.success'
format.json { render :json =>{:result => "ok", :message=>"Invitation #{params[:id]} was destroyed", :resource_id=>params[:id] } }
else
format.json { render :json => { :result=>"failed", :error=>"Cannot find Invitation #{params[:id]}", :resource_id=>params[:id] } }
end
end
end
end
この助けを願っています。