Когда я хочу отредактировать свою форму или когда есть ошибки проверки, я не могу предварительно заполнить поле ассоциации.
Если я добавляю label_method для имени, я получаю сообщение об ошибке undefined method `name' for ["Yes", true]:Array
В качестве альтернативы, когда я удаляю label_method, формаполе содержит только 'Да' вместо названия поля (имя 'room').
new.js.erb
$("#dynamic-rooms").empty();
<% @rooms.each do |acc| %>
$("#dynamic-rooms").append('<option value="<%= acc.id %>"><%= acc.name %></option>')
<% end %>
form.html.erb
<%= simple_form_for [@hotel, @reservation] do |f|%>
<%= f.simple_fields_for :rooms do |room| %>
<%= room.input :room_type, collection: @room_type_list, prompt: "Select type of room", label:false,
input_html:{
id: "room_type"
}%>
<% end %>
<%= f.association :room, collection: @rooms, input_html:{
value: @rooms.object_id,
id: "dynamic-rooms"
} %>
<% end %>
<% end %>
<script>
$(document).ready(function(){
var room_type = $("#room_type").val();
$.ajax({
url: "/hotels/<%= @hotel.id %>/reservations/new",
method: "GET",
dataType: "json",
data: {room_type: room_type},
error: function (xhr, status, error) {
console.error('AJAX Error: ' + status + error);
},
success: function (response) {
}
});
});
$(document).on("change", "#room_type", function(){
var room_type = $("#room_type").val();
$.ajax({
url: "/hotels/<%= @hotel.id %>/reservations/new",
method: "GET",
dataType: "json",
data: {room_type: room_type},
error: function (xhr, status, error) {
console.error('AJAX Error: ' + status + error);
},
success: function (response) {
}
});
});
</script>
контроллер
class ReservationsController < ApplicationController
# skip_before_action :authenticate_user!
def new
@user = current_user
@hotel = Hotel.find(params[:hotel_id])
@reservation = Reservation.new
@room_type_list = @hotel.room_types
@rooms = []
if params[:room_type].present?
@rooms = RoomType.find(params[:room_type]).rooms
end
if request.xhr?
respond_to do |format|
format.json {
render json: {rooms: @rooms}
}
format.js
end
end
authorize @reservation
end
def create
@user = current_user
@hotel = Hotel.find(params[:hotel_id])
@reservation = Reservation.new(reservation_params)
@reservation.hotel = @hotel
authorize @reservation
if @reservation.save
redirect_to hotel_path(@hotel)
else
# @room_type = @reservation.room.room_type
@room_type_list = @hotel.room_types
# @room = @reservation.room
render 'new'
end
end
private
def reservation_params
params.require(:reservation).permit(:room_id, :arrival, :departure, :payment, :reservation_contact_id, option_ids:[],
reservation_contact_attributes: [:id, :first_name,
:last_name, :zipcode, :city, :street, :street_number],
rooms_attributes: [:id,:name, :room_type_id,
room_types_attributes: [:id, :name]])
end
end