2012-12-13 62 views
0

在我的Rails應用程序中,我正在尋找一種方法來保存帖子,並提出一條說明「已保存」的通知。沒有重定向到任何地方。Ruby on Rails保存使用AJAX

我可以在控制器中執行此操作,還是必須使用Ajax?如果我必須使用Ajax,是否有一種簡單的方法來實現它?

以下是我的控制器的創建和更新操作:

def create 
    @document = current_user.documents.build(params[:document]) 

    if @document.save 
    redirect_to @document.edit, notice: 'Saved' 
    else 
    render action: "new" 
    end 
end 

def update 
    @document = current_user.documents.find_by_url_id(params[:id]) 

    if @document.update_attributes(params[:document]) 
    redirect_to @document, notice: 'Saved' 
    else 
    render action: "edit" 
    end 
end 

回答

0

貌似你試圖取代「新文件」的形式與編輯文檔形式以及顯示警告稱它被保存了。

說實話,你可能最簡單的方法是使用jQuery替換整個表單。這不是最簡單的,有辦法做所有的Javascript客戶端,但這會讓你開始。

假設你有你的「新建文檔」形式的部分稱爲_new.html.erb創建一個名爲create.js.erb文件,並把這個在它:

$edit_form = "<%= escape_javascript(render :partial => 'new', :locals => {document: @document}) %>" 
$("#document_form_container").html($edit_form) 

然後確保你的窗體有在form_for標籤:remote => true

+0

是嗎?我有'_form.html.erb'和'new.html.erb'。我目前使用jQuery,所以使用它會很好。我是否需要用自己的ID替換'#document_form_container'? – user1658756

+0

是的,並且在渲染中使用'form'代替'new':partial。 –

+0

控制器中的新動作?我會怎麼做?道歉,我是Rails的新手 – user1658756

0

如果你不希望創建一個新的控制器動作(你可能不應該),那麼我建議你設置你的創造和更新操作看起來是這樣的:在應用

def create 
    @document = current_user.documents.build(params[:document]) 

    if @flag = @document.save 
    respond_to do |format| 
     format.html 
     format.js 
    end 
    else 
    render action: "new" 
    end 
end 

def update 
    @document = current_user.documents.find_by_url_id(params[:id]) 

    if @flag = @document.update_attributes(params[:document]) 
    respond_to do |format| 
     format.html 
     format.js 
    end 
    else 
    render action: "edit" 
    end 
end 

然後/views/documents/create.js.erb:

var results_html; 
var status; 

<% if @flag %> 
    results_html = $('<%= j(render("document"))%>'); 
    status = "success"; 
<% else %> 
    results_html = $(''); 
    status = "failure"; 
<% end %> 

$('destination').append(results_html); //assuming you're inserting a list item or some content besides the alert onto the page 

alert(status); // replace this with your actual alert code 

和update.js.erb:

var results_html; 
var status; 

<% if @flag %> 
    results_html = $('<%= j(render("document"))%>'); 
    status = "success"; 
<% else %> 
    results_html = $(''); 
    status = "failure"; 
<% end %> 

$('#<%= @document.id %>').replaceWith(results_html); //assuming you're replacing a list item or some content besides the alert onto the page. also, make sure you're searching for the correct element id 

alert(status); // replace this with your actual alert code 

希望這有助於。關鍵是使用rails可以爲控制器操作上的不同訪問方法定義不同的模板。當你發出一個AJAX請求時,你將默認獲得js.erb視圖,這將允許你通過返回當服務器返回時運行的javascript來操作當前頁面。

+0

如何在_form.html.erb上添加遠程真? – user1658756