【发布时间】:2019-12-05 13:37:28
【问题描述】:
在我的预订表格中,我想创建一个用户可以预订一个房间的情况。由于我需要为预订的房间提供唯一标识符,因此我使用了通过reservation_rooms 链接房间和预订的设置。
-
reservation_room属于reservation和room - 一个
reservationhas_oneroom
问题
我试图让用户选择一个房间,然后用这个reservation 和room picked 构建reservation_room 模型
我目前的设置不允许我首先获得房间(在创建操作中):
Processing by ReservationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"YfVsfb4po0Dl/kycf9Mm6LMYCXi7+GLDUpe8gANaGRMNzPiCoq6HC9CWarSyJjLmYG1/hE6D7w==", "reservation"=>{"arrival"=>"2019-12-05", "departure"=>"2019-12-06", "room_id"=>"7"}, "commit"=>"Search", "hotel_id"=>"22"}
Room.find(params[:room_id])
ActiveRecord::RecordNotFound: Couldn't find Room without an ID
代码
型号
models
class Reservation < ApplicationRecord
belongs_to :hotel
has_one :reservation_room, dependent: :destroy
has_one :room, through: :reservation_rooms
end
class ReservationRoom < ApplicationRecord
belongs_to :room
belongs_to :reservation
end
class Room < ApplicationRecord
belongs_to :room_category
has_many :reservation_rooms
has_many :reservations, through: :reservation_rooms, dependent: :destroy
accepts_nested_attributes_for :room_category
end
reservations_controller
def new
@hotel = Hotel.find(params[:hotel_id])
@reservation = @hotel.reservations.new
@room_categories = @hotel.room_categories
@rooms = Room.where(room_category: @room_categories)
authorize @reservation
end
def create
@hotel = Hotel.find(params[:hotel_id])
@reservation = @hotel.reservations.new(reservation_params)
binding.pry
@room = Room.find(params[:room_id])
@reservation.build_reservation_room(room_id: @room.id)
authorize @reservation
if @reservation.save
authorize @reservation
redirect_to new_second_part_hotel_reservation_path(@hotel, @reservation)
end
end
private
def reservation_params
params.require(:reservation).permit(:room_id, :arrival, :departure,
reservation_room_attributes: [:room_id, :reservation_id],
rooms_attributes: [:id,:name, :room_category_id,
room_categories_attributes: [:id, :name]])
end
end
reservations/new.html.erb
<%= simple_form_for [@hotel, @reservation] do |f|%>
<%= f.input :arrival%>
<%= f.input :departure %>
<%= f.input :room_id, collection: @room_categories.order(:name), as: :grouped_select, group_method: :rooms, label:false %>
<%= f.button :submit %>
<% end %>
【问题讨论】:
-
可能需要更多信息,但参数的结构不是这样吗?参数[:reservation][:room_id]
-
在
app/models/reservation.rb中应该是has_one :room, through: :reservation_room(单数)
标签: ruby-on-rails activerecord simple-form