使用 Rails 4 处理创建操作

Handling a create action with Rails 4

我已经有一段时间没用 Rails 和 UJS 做过任何事情了(尤其是 Ajax 方面)。

我希望能够使用 ajax 创建对象并处理可能出现的任何验证错误。

所以我从我的表单开始(使用 remote: true)documents/new

<% form_for @document, remote: true do |f| %>
 <!-- form fields and submit button here -->
<% end %>

控制器(这是我有点卡住的地方)

这是我现在的,下面是我认为应该的

class DocumentsController < ApplicationController
  def create
    @document = current_user.documents.new(document_params)
  if @document.save
    redirect_to public_index_path, notice: 'Successfully Saved File'
  else
    render template: 'public/index'
  end
 end
end

要处理的控制器 ajax

class DocumentsController < ApplicationController
  def create
  @document = current_user.documents.new(document_params)
  respond_to do |format|
    if @document.save
      format.html { redirect_to public_index_path, notice: 'Successfully Saved Document'}
      format.js { # Does anything need to be here?}
    else
      format.html { render action: 'new' }
      format.js { render json: @document.errors }
    end
  end
end

在我看来我有documents/new。我需要相应的 .js.erb 文件吗?

通常我记得该文件看起来像

$('#idOfElement').html("<%= j render(:partial => 'shared/my_partial') %>")

更新

目前我收到 template is missing 创建操作错误

我的控制器目前看起来像这样

def create
@document = current_user.documents.new(document_params)
respond_to do |format|
  if @document.save
    format.html { redirect_to public_index_path, notice: 'Successfully Saved File' }
    format.js { }
  else
    format.html { render action: 'new' }
    format.js {  }
  end
end
end

您在 views/documents/ 中需要一个 create.js.erb 文件来处理您需要的 js 代码 运行 并将新记录放在页面上,讨论渲染部分。

例如,您的页面上有一个文档列表:

<div id="docs_list">
  <% @docs.each do |doc| %>
    <div id="doc#{doc.id}" class="document_item">
     ... doc content here
    </div>
  <% end %>
</div>

你的 create.js.erb 文件我们会有这样的东西:

<% if @document.valid? %>
  $("#new_document")[0].reset(); // this will reset the form
  $('.document_item').last().after('<%= j(render @document) %>'); // this will add the document to the list
<% else %>
  alert("Sorry, can not save document!");
<% end %>

请确保您在 views/documents 中有 _document.html.erb