Mel Mel - 1 month ago 12
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:

Proposal

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


Innovation

belongs_to :proposal


In my routes.rb, I have:

resources :proposals do
resources :innovations


In my proposals controller, I have:

def new
@proposal = Proposal.new
@proposal.innovations.build

# authorize @proposal
end

def edit
@proposal.innovations_build unless @proposal.innovations

end


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' %>
</div>


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

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.