[英]rails not making the link between dynamically added nested form and parent
I've got a form 'tasks' and I am dynamically adding a child 'steps' form. 我有一个“任务”表单,并且正在动态添加一个子“步骤”表单。
The 'steps' is added through a javascript call to render('steps/form'). “步骤”通过javascript调用添加到render('steps / form')。
The form loads fine, but when submitting the tasks form, the added step is not put into the database. 表单可以很好地加载,但是在提交任务表单时,添加的步骤不会放入数据库中。
I assume this is because I'm not linking the two forms together, but I'm not entirely sure. 我认为这是因为我没有将两个表单链接在一起,但是我不确定。
My code is Tasks/new.html.erb 我的代码是Tasks / new.html.erb
<%= form_for @task, :html=>{:multipart=>true} do |f| %> <%= f.label :task_name %> <%= f.text_field :task_name %> <%= link_to "Add Step", @step, :remote=>true, :class=>'addStep %> <%= f.submit %> <% end %> <% content_for(:js) do %> $('a.addStep').click(function(){ $('div#newStep').append("<%= escape_javascript(render('steps/form'))%>"); }); <% end %>
the steps/_form.html.erb is steps / _form.html.erb是
<p class="fields"> <%= fields_for :steps do |builder| %> <%= builder.label :title %> <%= builder.text_field :title %> <% end %>
I believe the problem is that i'm not passing 'f' or 'task' into the 'step' form, but I couldn't figure out how to do that. 我认为问题在于我没有将“ f”或“任务”传递给“步骤”形式,但是我不知道该怎么做。
You might have to update the params in your parent controller to include the attributes of the child. 您可能必须更新父控制器中的参数以包括子代的属性。 eg
例如
Class TasksController < ApplicationController
...
def task_params
params.require(:task).permit :name, :description ,
steps_attributes: [:step, :step_description, :due_date]
end
end
Class Task < ActiveRecord::Base
has_many :steps
accepts_nested_attributes_for :steps
end
Class Step < ActiveRecord::Base
belongs_to :task
end
Try something like this: 尝试这样的事情:
<%= render :partial => 'steps/form',
:locals => {:form => f} %>
Hope this helps. 希望这可以帮助。
Edit- 1 编辑-1
Do as follows: 进行如下操作:
<%= form_for @task, :html=>{:multipart=>true} do |f| %>
<%= f.label :task_name %>
<%= f.text_field :task_name %>
<div style="display:none;" id="steps_form">
<%= render :partial => 'steps/form',
:locals => {:form => f} %>
</div>
<%= link_to "Add Step", @step, :onClick=>"js_function_to_change_display_property()", :class=>'addStep' %>
<%= f.submit %>
<% end %>
then you can use simple javascript to view the steps form by changing the display property of steps_form. 那么您可以使用简单的javascript通过更改steps_form的显示属性来查看步骤表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.