如果你不希望創建一個新的控制器動作(你可能不應該),那麼我建議你設置你的創造和更新操作看起來是這樣的:在應用
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來操作當前頁面。
是嗎?我有'_form.html.erb'和'new.html.erb'。我目前使用jQuery,所以使用它會很好。我是否需要用自己的ID替換'#document_form_container'? – user1658756
是的,並且在渲染中使用'form'代替'new':partial。 –
控制器中的新動作?我會怎麼做?道歉,我是Rails的新手 – user1658756