Ruby on Rails使用AJAX保存

时间:2012-12-13 20:17:04

标签: javascript ruby-on-rails ruby ajax

在我的Rails应用程序中,我正在寻找一种方法来保存帖子并提出一条说“已保存”的通知。没有重定向任何地方。

我可以在控制器中执行此操作还是必须使用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

2 个答案:

答案 0 :(得分: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)

然后确保您的表单在:remote => true标记中有form_for

答案 1 :(得分: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

然后在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来操作当前页面。