1

When I click the 'New Schedule Status' button on the 'Project' show page, but the route that the error shows me is plural, when it should be singular. Here's my code:

# project.rb
class Project < ActiveRecord::Base
  has_one :schedule_status
end

# schedule_status.rb
class ScheduleStatus < ActiveRecord::Base
  belongs_to :project
end

# schedule_statuses_controller.rb
def new
  @project = Project.find(params[:project_id])
  @schedule_status = @project.build_schedule_status
end

# routes.rb
resources :projects do
  resource :schedule_status
end

# _form.html.erb
<%= form_for [@project, @schedule_status] do |f| %>
  ...

The error informs me that my form_for line is incorrect. It seems like my instance variables are setup correctly, but the error is:

undefined method `project_schedule_statuses_path` for ...

Any idea why the route it's attempting to access is plural?

ardavis
  • 9,842
  • 12
  • 58
  • 112

2 Answers2

1

This is a bug. form_for looks for the plural version of the object. However since you've declared a singular resource :schedule_status, the path helper method is never created.

To get around this you should use :url parameter for form_for.

Look at this question/answer for more clarity.

Community
  • 1
  • 1
Spidy
  • 39,723
  • 15
  • 65
  • 83
0

It is not a bug it is a feature (ticket closed as won't fix):

rails issue:

https://github.com/rails/rails/issues/1769

summary quote:

the error has been around for a long while however a clean solution doesn't readily represent itself. The polymorphic_url helper has no 'intelligence' in how it operates - it has no information about what you've declared as resources in your routes.rb. All it has to go on it the name of the model and how that maps to the named url helpers.

The problem is there is no easy way to discern whether a model maps to a singular or a regular resource url. Checking for the presence of a collection url doesn't work as the resource may have been specified with :except => :index and trying to rescue route generation errors doesn't work because passing an instance to a singular resource url helper will generate a url with the format set to the id and no exception.

rails issue closed in favour of the previous: https://github.com/rails/rails/issues/4978

conclusion:

in such cases you're supposed to give the url. url_for cannot reflect on routes to see if that's a resource or not.

Viktor Trón
  • 8,774
  • 4
  • 45
  • 48