Search code examples
ruby-on-railsformsnested-resources

Rails form - multiple nested routes undefined method '_path'


This app has the following models:

  1. Farm (has_many :crops)
  2. Crop (belongs_to :farm, has_many :issues)
  3. Issue (belongs_to :crop)

Here are the routes:

resources :farms do 
  resources :crops do 
    resources :issues
  end 
end

I want a user to be able to create a new "issue" from the Farm#show page that lists all the farm's crops. Here is the form that is causing the error on the Farm#show page:

undefined method `crop_issues_path' for #<#:0x007fa814a3cc30>

#from the show action on the controller:
#@farm = Farm.find(params[:id])
#@crops = @farm.crops

<% @crops.each do |crop| %>
<%= crop.id %>
  <%= form_for([crop, crop.issues.build]) do |f| %>
    <%= f.select(:issue_type, options_for_select([['mold'], ['pests'], ['dehydration'], ['other']])) %>
    <%= f.text_area :notes %><br>
    <%= f.submit "New Issue", :class => "button" %>
  <% end %> 
<% end %>

My create action on issues controller:

  def create
    @crop = Crop.find(params[:crop_id])
    @issues = @crop.issues.create(params[:issue].permit(:issue_type, :notes, :crop_id))

    redirect_to :back
  end

I have used nearly identical code when the crops and issues were not nested under farms, and it works. I believe the issue is because of the nesting, but cannot figure out a solution.


Solution

  • I think your problem is with the object you're binging the form to. It should be @farm, as you're in the @farms show action.

    I modified it to this:

    <% @crops.each do |crop| %>
    <%= crop.id %>
      <%= form_for([@farm, crop, crop.issues.build]) do |f| %>
        <%= f.text_area :notes %><br>
        <%= f.submit "New Issue", :class => "button" %>
      <% end %> 
    <% end %>
    

    with my controller like this:

    class FarmsController < ApplicationController
      def index
      end
    
      def show
        @farm = Farm.find_by_id(params[:id])
        @crops = @farm.try(:crops)
      end
    end