mercredi 24 février 2016

how to access child new form from parent index page in rails?

I am trying to fetch booking controller's new form, from the cab index page. how can i fetch it? how can access the new form from cab index page where i have shown all the cabs which are added..

cab controller

    class CabsController < ApplicationController


before_action :find_cab, only: [:show, :edit, :update, :destroy]

def index
    @cabs = Cab.all.order("created_at DESC")
end

def new
    @cab = Cab.new
end

def show
    @reviews = Review.where(cab_id: @cab.id).order("created_at DESC")

    if @reviews.blank?
      @avg_review=0
    else
      @avg_review=@reviews.average(:rating).round(2)
    end
end

def edit
end

def create
    @cab = Cab.new(cab_params)
    if @cab.save
        redirect_to @cab
    else
        render 'new' 
    end
end

def update
    if @cab.update(cab_params)
        redirect_to @cab
    else
        render 'edit'
    end
end

def destroy
    @cab.destroy

    redirect_to root_path
end

private

def find_cab
    @cab = Cab.find(params[:id])
end


def cab_params
    params.require(:cab).permit(:name, :number_plate, :seat, :image)
end 
end

booking controller

    class BookingsController < ApplicationController

before_action :find_booking, only: [:show, :edit, :update, :destroy]
before_action :find_cab

def index
 @bookings = Booking.where(cab_id: @cab.id).order("created_at DESC")
end

def new
 @booking = Booking.new
end

def show
end

def edit
end

def create
  @booking = Booking.new(booking_params)
  @booking.user_id = current_user.id
  @booking.cab_id = @cab.id

  if @booking.save
   redirect_to cab_booking_path(@cab, @booking)
 else
   render 'new'
 end
end

def update
end

def destroy
end

private

def find_booking
  @booking = Booking.find(params[:id])
end

def find_cab
  @cab = Cab.find(params[:cab_id])
end

def booking_params
  params.require(:booking).permit(:date, :address, :start_destination, :destination, :start_date, :end_date, :contact_no)
end

end

routes

     resources :cabs  do
       resources :bookings
     end

cab/index.html.erb

    <div class="container">
<h2>All Cabs</h2>
<div class="row">


    <% @cabs.each do |cab| %>
        <div class="col-sm-6 col-md-3">
            <div class="thumbnail">
                <%= link_to image_tag(cab.image.url(:medium), class: 'image'), cab %><br>
                Cab Name : <h4><%= cab.name %></h4>
                <%= link_to "Book Now", new_cab_booking_path(@cab, @booking) %> # i wanted to create this link
            </div>
        </div>
    <% end %>
</div>
<%= link_to "Add Cab", new_cab_path, class: 'btn btn-default' %>

the error i am getting is

    No route matches {:action=>"new", :cab_id=>nil, :controller=>"bookings"} missing required keys: [:cab_id]

Aucun commentaire:

Enregistrer un commentaire