Mel Mel - 1 year ago 115
Ruby Question

Rails 5, Simple Fields For with Cocoon gem for nested resources

I am trying to learn how to use namespaced routes.

I have a model called Proposal and another called Innovation. The associations are:


has_many :innovations
accepts_nested_attributes_for :innovations, reject_if: :all_blank, allow_destroy: true


belongs_to :proposal

In my routes.rb, I have:

resources :proposals do
resources :innovations

In my proposals controller, I have:

def new
@proposal =

# authorize @proposal

def edit
@proposal.innovations_build unless @proposal.innovations


In my proposal form, I am trying to nest the form fields for the innovation model.

<%= f.simple_fields_for [@proposal, @innovation] do |f| %>
<%= f.error_notification %>
<%= render 'innovations/innovation_fields', f: f %>

<% end %>

<%= link_to_add_association 'Add another novel aspect', f, :innovations, partial: 'innovations/innovation_fields' %>

When I try this, I get an error that says:

undefined method `model_name' for nil:NilClass

I get the same error when I try:

<%= f.simple_fields_for [@proposal, @innovations] do |f| %>

Can anyone see what I need to do in order to have the proposal form include the innovation form fields?

Answer Source

You are using nested-attributes, so in this particular case there is no need for nested routes. You can just write

<%= f.simple_fields_for @proposal do |f| %>

This will post the form, containing all the innovations, to the ProposalsController.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download