Nekron
Nekron

Reputation: 123

Undefined method `_path

I have a little problem with creating new object, called "round". I'm getting the following error:

NoMethodError in Rounds#new

undefined method `rounds_path'

rounds_controller.rb:

  def new
    @round = Round.new
  end

  def create
    @round = Round.new(round_params)
  end

  private

  def round_params
    params.require(round).permit(:tournament_id)
  end

View for action new:

      %h2 New round
      = simple_form_for @round do |r|
        = r.input :number, label: 'Round number'
        = r.button :submit, class: "btn btn-primary"

Routes.rb:

  resources :tournaments do
    resources :rounds
  end

I think that problem is in nesting, but I don't know where exactly.

Upvotes: 0

Views: 188

Answers (2)

j-dexx
j-dexx

Reputation: 10416

Rails guesses at routes, which is useful. Because you're only passing round it routes to rounds_path, so as you suspect it's because you've nested it. Change this

= simple_form_for @round do |r|

to

= simple_form_for [@tournament, @round] do |r|

As Max says, you will need to have got the tournament. I assumed you'd have done this with a before_action in your controller. I would then create rounds via the tournament personally

class RoundsController

  before_action :set_tournament

  def new
    @round = @tournament.rounds.new
  end

  def create
    @round = @tournament.rounds.new(round_params)
  end

  private

  def set_tournament
    @tournament = Tournament.find(params[:tournament_id])
  end

  def round_params
    params.require(:round).permit(:number)
  end
end

Upvotes: 2

Bryan Dimas
Bryan Dimas

Reputation: 1452

You can specify the url to which the simple form will post to.

%h2 New round
      = simple_form_for @round, url: tournament_rounds_path(tournament_id: params[:tournament_id]) do |r|
        = r.input :number, label: 'Round number'
        = r.button :submit, class: "btn btn-primary"

For future reference, you can check the actual routes that your routes.rb creates by running rake routes on your terminal.

Upvotes: 1

Related Questions