Search code examples
ruby-on-railsroutesembedded-resource

Ruby on Rails - routing error when using nested resources with form helper


So I have a relationship where service has_many statuses

I have this in my routes.rb file

resources :services do
  resources :statuses
end

and this is my statuses_controller file

class StatusesController < ApplicationController
  def new
    @status = Status.new(:parent_id => params[:parent_id])
  end  

  def create
    @service = current_user.services.find(params[:id])
    @status = Status.new(params[:status])
    if @status.save
      flash[:notice] = "New status created."
    else
      flash[:error] = "Error creating new status."
    end
    redirect_to service_statuses_path
  end
end

and I'm getting an error:

undefined method `statuses_path' for #<#<Class:0x000001045dbb28>:0x00000104554e48>

when trying to load:

http://localhost:3000/services/2/statuses/new

with the file views/statuses/new.html.erb

<%= form_for [@service, @status], :path =>service_statuses_path do |f|%>
  <%= f.label :status %>
  <%= f.text_field :state %><br />

  <%= f.submit %>
<% end %>

Why is it giving me an undefined method `statuses_path' still?


Solution

  • Not sure this is the cause of error. But you have to change the method call

    service_statuses_path
    

    to

    service_statuses_path(@service, @status)
    

    which will generate the path like below.

    /services/service_id/statuses/status_id