如果您不想创建新的控制器操作(并且您可能不应该),那么我建议您将创建和更新操作设置为如下所示:
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
然后在 app/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 来操作当前页面。