tvieira
tvieira

Reputation: 1915

undefined method `bookings_path'

I have a form to fill in booking details, but I'm getting the following error:

NoMethodError in Bookings#new
undefined method `bookings_path'

This happened after change the routes.rb file, to nest the booking resources in the user resource.

My form file code is the following:

<% provide(:title, 'Book Now!') %>

<section id="book-now">

    <%= form_for(@booking) do |f| %>

    <header>
        <h1>Edit booking</h1>
    </header>

        <%= f.text_field :name,         placeholder: "Name" %>
        <%= f.text_field :check_in,     placeholder: "Check-in" %>
        <%= f.text_field :check_out,    placeholder: "Check-out" %>

        <%= f.submit "Save" %>     

    <% end %>

</section>

My booking controller code is:

class BookingsController < ApplicationController

  def new
    @booking = Booking.new
  end

  def create
    @booking = Booking.new(params_bookings)
    @booking.user_id ||= current_user.id  
      if @booking.save
          redirect_to user_path(@booking.user_id)
      else
        # render 'new'
      end
    end
  end

  private

  def params_bookings
    params.require(:booking).permit(:check_in, :check_out, :name, :user_id)
  end

end

and my routes.rb file looks like this:

Hightide::Application.routes.draw do

  resources :users do
    resources :bookings

  end

  match '/users/:user_id/bookings/new',       to: 'bookings#new', via: [:post, :get]

Upvotes: 0

Views: 258

Answers (1)

Nikolay
Nikolay

Reputation: 1392

you have this error because your bookings routes are nested to the users, so when you write this

form_for @booking

you essentially call

form_for bookings_path, ...

coz rails gets the type of the object you send to form_for and tries to get vanilla path for it.

to solve the problem you need either create the vanilla bookings resources in your routes, or specify both a user and a booking reference for the form_for call, like so

form_for [current_user, @booking]

Upvotes: 1

Related Questions