Ben Muschol
Ben Muschol

Reputation: 607

Routing error with forms for nested resources

I have a rounds resource nested within the cases resources, so my routes.rb file looks like this:

resources :cases do
  resources :rounds
end

My create action in the controller looks like this:

def create
  @round = Round.new(round_params)
  if @round.save
    flash[:success] = "Round added"
    redirect_to case_path(id: @round.case_id)
  else
    render 'new'
  end
end

and my _round_form.html.erb view looks like this:

<%= form_for [@case, @round] do |f| %>
    <%= render 'shared/error_messages', object: @round %>

    ...

    <%= f.submit "Submit", class: "btn btn-primary form-button case-button" %>
<% end %>

For some reason, when I properly create a round, it works, but when I submit a round with errors, instead of rendering the error messages, it gives me this error:

undefined method rounds_path' for #<#<Class:0xc8b7508>:0xc8b6da0>

Why is this happening? Shouldn't it be looking for new_case_round_path, instead of rounds_path?

Thew new action, if that helps:

def new
  id = params[:case_id]
  unless id
    flash[:danger] = "You must pick a case before trying to log a round"
    redirect_to 'pick_case'
  end
  @case = Case.find(id)
  @side_options = @case.sides.map { |s| [s.name, s.id] }
  @round = Round.new
end

Upvotes: 1

Views: 47

Answers (2)

Prashant4224
Prashant4224

Reputation: 1601

Hope you have the @case value, Try this:

<%= form_for([@case, @round]) do |f| %>
  <%= render 'shared/error_messages', object: @round %>
  ...

  <%= f.submit "Submit", class: "btn btn-primary form-button case-button" %>
<% end %>

UPDATE

def new
  @side_options = @case.sides.map { |s| [s.name, s.id] }
  @round = @case.rounds.new
end

private

def set_case
   @case = Case.find(params[:case_id])
end

Upvotes: 1

Ben Muschol
Ben Muschol

Reputation: 607

The issue was the my @case was nil, so I added @case = Case.find(params[:case_id]) to the else branch of my create action

Upvotes: 1

Related Questions