Undefined method [model] _url for a nested resource

I am working on a project with nested resources and get an error message in the step controller:

def create @step = Step.new(step_params) respond_to do |f| if @step.save f.html { redirect_to @step, notice: 'Step was successfully created.' } f.json { render action: 'show', status: :created, location: @step } else f.html { render action: 'new' } f.json { render json: @step.errors, status: :unprocessable_entity } end end end 

I get an error:

 undefined method 'step_url' for #<StepsController:0x007feeb6442198> 

My routes look like this:

 root 'lists#index' resources :lists do resources :steps end 
+9
source share
1 answer

Since you are using nested resources, update the create action as shown below:

  def create @list = List.find(params[:list_id]) @step = @list.steps.build(step_params) ## Assuming that list has_many steps respond_to do |f| if @step.save ## update the url passed to redirect_to as below f.html { redirect_to list_step_url(@list,@step), notice: 'Step was successfully created.' } f.json { render action: 'show', status: :created, location: @step } else f.html { render action: 'new' } f.json { render json: @step.errors, status: :unprocessable_entity } end end end 

Run rake routes to see the available routes. Since the route to step # show will look something like this:

 GET lists/:list_id/steps/:id steps#show 

Use list_step_url with 2 arguments @list For: list_id and @step for: id to go to the step show page.

+15
source

All Articles