我正在嘗試製作停車場預訂應用程序和一般預訂工作。當我輸入user id
,spot id
然後選擇is_booked
。現在我希望點列表旁邊的按鈕以相同的方式工作,但我無法獲得該點的 id,如下所示:
<% @spots.each do |spot| %>
<tr>
<td><%= spot.name %></td>
<td><%= link_to 'Show', spot %></td>
<td><%= link_to 'Edit', edit_spot_path(spot) %></td>
<td><%= link_to 'Booking', new_booking_path %></td>
</tr>
<% end %>
</tbody>
目前的路徑是 new_booking 但僅用於預覽,最終它將是 create_booking。
我嘗試了幾種方法,但都沒有奏效,我可以引用所有 ID,但不能引用單個 ID。這是從booking_controller 到new_booking 定義的示例,我給出了以下參數:
@booking = current_user.bookings.build(:spot_id => Spot.ids, :is_booked => true)
我希望我已經清楚地描述了這個問題。我對 ruby 相當陌生,這似乎是一個我不知道如何修復的微不足道的錯誤。請幫忙。
解決這個問題的 Rails 方法是創建一個嵌套路由:
resources :spots do
resources :bookings, shallow: true
end
這將創建路徑/spots/:spot_id/bookings
,這意味著點 ID 作為 URL 的一部分傳遞。
class BookingsController < ApplicationRecord
before_action :set_spot, only: [:new, :create, :index]
before_action :set_booking, only: [:show, :edit, :update, :destroy]
# GET /spots/1/bookings/new
def new
@booking = @spot.bookings.new
end
# POST /spots/1/bookings
def create
@booking = @spot.bookings.new(booking_params) do |b|
b.user = current_user
end
respond_to do |format|
if @booking.save
format.html { redirect_to @booking, notice: "Booking was successfully created." }
format.json { render :show, status: :created, location: @booking }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @booking.errors, status: :unprocessable_entity }
end
end
end
private
def set_spot
@spot = Spot.find(params[:spot_id])
end
def set_booking
@booking = Booking.find(params[:id])
end
def booking_params
params.require(:booking)
.permit(:starts_at)
end
end
# app/views/bookings/new.html.erb
<%= render partial: 'form' %>
# app/views/bookings/_form.html.erb
<%= form_with(model: [@spot, @booking]) |form| %>
# ...
<%= form.submit %>
<% end %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句