将表单对象传递给来自ajax请求的部分呈现 [英] Passing a form object to a partial rendered from an ajax request

查看:181
本文介绍了将表单对象传递给来自ajax请求的部分呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有某些嵌套属性模型的事件表单.从选择框中选择客户端后,将呈现其他模型.观察者观察并调用控制器动作,该动作呈现包含fields_for嵌套模型的部分.我遇到的问题是我无法将事件"form"块传递给新呈现的部分-至少我不知道如何...

I have an event form with some nested attribute models. The additional models are rendered after a client is selected from a select box. An observer watches and calls a controller action which renders a partial containing the fields_for nested models. The issue I'm having is that I can't pass the event 'form' block to the newly rendered partial - at least I can't figure out how...

以下代码引发错误:参数数量错误(0表示1)".任何帮助或建议,表示赞赏.如下所述,如果您可以提供这种情况的示例,我也愿意使用不引人注目的JavaScript重新实现此功能.

The code below raises the error: "wrong number of arguments (0 for 1)". Any help or suggestions are appreciated. As mentioned below, I'm also willing to re-implement this using unobtrusive JavaScript if you can provide an example for this scenario.

活动表格:

<%- form_for @event do |form| %>

  <%= select_tag :id=>event_client_id %>
  <%= observe_field :event_client_id, url => {:action => 'client_questions'}, :with => "'client_id=' + encodeURIComponent(value)+'&event_id='+#{@event.id} %>

事件控制器

 def client_questions
   @event = Event.find(params[:event_id])
   @client = Client.find(params[:client_id])
   @client_questions = @client.questions.active
   respond_to do |format|
     format.js {
       render :update do |page|
         page[:client_questions].replace_html :partial => 'client_questions', :layout => false
       end
     }
   end
 end

_client_questions.html.erb部分

_client_questions.html.erb partial

<%- form.fields_for :client, @client do |client| %>
  <%= client_text_field :name %>

  <%- client.fields_for :questions do |question| %>
    <%=question.text_field :content %>

推荐答案

因此,您的主表单是在一个动作中呈现的,您希望将表单对象从该视图传递到在第二部分中呈现的另一个视图吗?这不是您可以做的,但是您可以在第二次渲染的局部渲染中修改视图代码,以便无需现有的表单对象就可以渲染它,例如:

So your main form is rendered in one action, and you're hoping to pass the form object from that view, to another view rendered in a second partial? That's not something that you can do, but you can modify your view code in the partial rendered the second time, so that it renders without needing the existing form object, something like:

<%- fields_for "event[client_attributes]", @client do |client| %>
  <%= client_text_field :name %>

  <%- client.fields_for :questions do |question| %>
    <%= question.text_field :content %>

我还没有运行此代码来对其进行测试,因此,将其生成的html与您现有的部分(如果以与主窗体相同的方式呈现)将生成的html进行比较.

I haven't run this code to test it, so compare the html it generates with the html that your existing partial would generate if it was rendered in the same action as the main form.

这篇关于将表单对象传递给来自ajax请求的部分呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆