I am trying to build a form with nested resources in my rails 4 app. I am using the cocoon gem. Each step will have substeps, and I'd like to allow the user to add as many substeps to the form and he/she would like.
Step.rb
class Step < ActiveRecord::Base
has_many :substeps
accepts_nested_attributes_for :substeps
Substep.rb
class Substep < ActiveRecord::Base
belongs_to :step
form code
<%= form_for :step, :url => steps_path do |f| %>
<%= text_field(:step, :title, :value => '', class: 'fly-input input_info', placeholder: 'Process Title', id: 'step_form_title') %>
<%= text_field(:step, :description, :value => '', class: 'fly-input input_info', placeholder: 'Process Description', id: 'step_form_description') %>
<%= hidden_field :step, :known %>
<%= hidden_field_tag :experiment, @experiment.id %>
<%= f.fields_for :substep do |ff| %>
<%= ff.text_field :description %>
<% end %>
<%= link_to_add_association 'Add substep', f, :substeps %>
<%= f.submit "Done", class: "main_button" %>
<% end %>
When I do this, I get an error reading: "undefined method `reflect_on_association' for NilClass:Class" on this line
<%= link_to_add_association 'Add substep', f, :substeps %>
Any thoughts on my problem?
EDIT Changed text_field to ff.text_field based on Pavan's suggestion
Cocoon expects that you provide a form object as second parameter, as you do, but also expects that this second parameter will have actually Rails model instance as attribute f.object
.
Your form is created just with model name so form_for :step
so Cocoon raises an exception.
To solve this you should change it to form_for @step
where @step
can be Step.new
or any other Step
instance.