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').
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
<%= 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
<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.
Try something like this:
<%= render :partial => 'steps/form',
:locals => {:form => f} %>
Hope this helps.
Edit- 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.
You might have to update the params in your parent controller to include the attributes of the child. e.g.
controllers/task_controller.rb
Class TasksController < ApplicationController
...
def task_params
params.require(:task).permit :name, :description ,
steps_attributes: [:step, :step_description, :due_date]
end
end
models/task.rb
Class Task < ActiveRecord::Base
has_many :steps
accepts_nested_attributes_for :steps
end
models/step.rb
Class Step < ActiveRecord::Base
belongs_to :task
end
精彩评论