【问题标题】:Rails remote form, replace after createRails 远程表单,创建后替换
【发布时间】:2013-05-07 23:51:36
【问题描述】:

我有一个典型的“创建”表单操作,它被设置为远程调用。

我想做的是在提交表单后,将表单替换为带有附加表单字段的“编辑”视图,这样一旦他们提交第二个表单,它就会更新而不是创建新记录。

所以基本上,表单会从“创建”变为“编辑”......但都是通过 ajax 调用。

我正在运行 Rails 3.2。

【问题讨论】:

  • 您可以让您的操作响应 js 并添加一个 create.js.erb 并在那里添加类似 $('#new_product_form').html('<%= escape_javascript(render("edit_product_form"))%>'); 的内容。

标签: ruby-on-rails ajax forms


【解决方案1】:

您向/resources 发送 AJAX POST

控制器

def create
  ...
  # you set @resource to be used in edit form
  @resource = Resource.create params[:resource]

  respond_to do |format|
    # tell controller to respond to requests with JS format
    format.js
  end
  ...
end

实际上,如果您只想要这种行为,您可以删除控制器中的任何内容。

def create
  ...
  # you set @resource to be used in edit form
  @resource = Resource.create params[:resource]
  ...
end

请务必使用 JS 格式的 POST:

<%= form_for @resource, format: :js %>

查看

文件create.js.erb 由控制器提供服务,并由浏览器运行。

$(selector).html("<%= escape_javascript( render 'edit') %>")

您必须根据页面中的新项目表单定义selector

文件_edit.html.erb在前一个文件中呈现为内联

<%= form_for @resource, remote: true do %>
  ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多