2

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.

1 Answers1

1

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
Andrew
  • 375
  • 2
  • 12
  • adding the "@farm" in the form_for seemed to be what fixed the issue! not familiar with the "@farm.try(:crops)" and how it is different from "@farm.crops" - what is the difference? – user1510700 Oct 02 '17 at 03:20
  • Ah sorry, that was my being lazy - didn't want to add crops into my db to test the scenario, so I added the `.try()` so it didn't blow up with null value for `@crops` – Andrew Oct 02 '17 at 16:18