我正在制作一个用户可以预订一小时培训的应用程序。我想让用户选择在培训中预订谁(小时),我在培训中进行索引预订,这是我的代码:
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>
该应用程序给我错误:
显示 /home/cesar/Apps/boxApp/app/views/bookings/_index_bookings.html.erb 第4行提出的地方:
没有路线匹配{:action =&gt;&#34; index&#34;,:controller =&gt;&#34;预订&#34;,:id =&gt;&#34; 7&#34;} 缺少必需的密钥:[:training_id]
我想知道为什么它不接受training_id,如果它取的是7级的id。以及如何修复它。
答案 0 :(得分:1)
使用嵌套资源网址时,应将父资源作为第一个参数传递,如下所示:
training_bookings_path(@training)