1

我正在做一個應用程序,用戶可以預約一個小時的訓練。我想給用戶看到是誰在訓練(小時)預訂的選項,我正在做一個培訓指標預訂,這是我的代碼:試圖創建一個小時訓練預訂索引

class BookingsController < ApplicationController 
    before_action :load_training, only: [:create] 

    def new 
    @booking = Booking.new 
    @training = Training.find(params[:training_id]) 
    @booking.training_id 
    end 

    def create 
    @booking = @training.bookings.build(booking_params) 
    @booking.user = current_user 

    if @booking.save 
     flash[:success] = "Book created" 
     redirect_to trainings_path 
    else 
     render 'new' 
    end 
    end 


    def index 
    @bookings = Booking.all 
    end 


    def destroy 
    @booking = Booking.find(params[:id]) 
    @booking.destroy 
    flash[:success] = "Book deleted" 
    redirect_to trainings_path 
    end 



private 
    def booking_params 
    params.require(:booking).permit(:user_id, :training_id) 
    end 

    def load_training 
    @training = Training.find(params[:training_id]) 
    end 

end 

預訂模型:

class Booking < ApplicationRecord 
    belongs_to :user 
    belongs_to :training 
    default_scope -> { order(created_at: :desc) } 
    validates :user_id, presence: true 
    validates :training_id, presence: true 



end 

我的routes.rb:

Rails.application.routes.draw do 

    root 'static_pages#home' 
    get '/signup',    to: 'users#new' 
    get '/contact',    to: 'static_pages#contact' 
    get '/about',    to: 'static_pages#about' 
    get '/login',    to: 'sessions#new' 
    post '/login',    to: 'sessions#create' 
    delete '/logout',    to: 'sessions#destroy' 
    get '/book',     to: 'bookings#new' 
    post '/book',     to: 'bookings#create' 
    delete '/unbook',    to: 'bookings#destroy' 


    resources :account_activations, only: [:edit] 
    resources :password_resets,  only: [:new, :create, :edit, :update] 

    resources :trainings do 
    resources :bookings 
    end 
    resources :users 
end 

當我去訓練表演(培訓特定的小時)的代碼如下:

<div class="row"> 
    <section> 
     <h1> 
HOUR: <%= @training.hour %> 
     </h1> 
    </section> 
    <section> 
     <h1> 
SLOTS: <%= @training.slots %> 
     </h1> 
    </section> 
    <center> 
    <%= render 'bookings/booking_form' if logged_in? %> 
    <%= render 'bookings/index_bookings' if logged_in? %> 
    </center> 

的_index_bookings.html.erb是:

<ul class="bookings"> 
<% if current_user.bookings(@training) %> 
    <li> 
<%= link_to @training_id, training_bookings_path %> 
</li> 
<% end %> 
</ul> 

的應用程序給我的錯誤:

Showing /home/cesar/Apps/boxApp/app/views/bookings/_index_bookings.html.erb where line #4 raised:

No route matches {:action=>"index", :controller=>"bookings", :id=>"7"} missing required keys: [:training_id]

我想知道爲什麼它不走training_id,如果是以7的類的id爲準,以及如何解決它。

+1

嘗試加入其更改爲這樣:'training_bookings_path(@training)' – eiko

+0

感謝,它的工作。上帝保佑你 –

+0

很高興幫助!我添加它作爲答案,現在我們知道它的工作原理。如果你有機會接受答案,它會幫助其他有相同問題的用戶。謝謝! – eiko

回答

1

當使用嵌套資源URL,你應該通過父資源作爲第一個參數,像這樣:

training_bookings_path(@training) 
相關問題