我有一个预订版本的BookingPost。 在booking_posts / show.html.erb中我有:
<div class="card-action">
<%= form_for([@reservation.booking_post, @reservation], html: {multipart: true}, class: "col s12") do |f| %>
<% if @reservation.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@reservation.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @reservation.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="col s6">
<%= f.label :start %>
<%= f.date_field :start, placeholder: "start time", class: "datepicker" %>
</div>
<div class="col s6">
<%= f.label :end %>
<%= f.date_field :end, placeholder: "end time", class: "datepicker" %>
</div>
<div class="col s6">
<%= f.label :reservation_time %>
<%= f.time_field :reservation_time, placeholder: "time", class: "timepicker", id: "timepicker", type: "time" %>
</div>
<div class="input-field col s6">
<%= f.label :name %>
<%= f.text_field :name, class: "validate" %>
</div>
<div class="input-field col s6">
<%= f.label :email %>
<%= f.text_field :email, class: "validate" %>
</div>
<div class="input-field col s6">
<%= f.label :phone_number %>
<%= f.text_field :phone_number, class: "validate" %>
</div>
<div class="waves-effect waves-light btn">
<%= f.submit t(:submit_reservation)%>
</div>
<% end %>
<br>
</div>
booking_posts_controller:
# GET /booking_posts/1
# GET /booking_posts/1.json
def show
@booking_picture = @booking_post.booking_pictures.build
@booking_pictures = @booking_post.booking_pictures
@reservation = @booking_post.reservations.build
@reservations = @booking_post.reservations
end
reservations_controller:
# GET /reservations/new
def new
@reservation = Reservation.new
end
def create
@booking_post = BookingPost.find(params[:booking_post_id])
@email= User.where(admin: true).first.email
@reservation = @booking_post.reservations.build(reservation_params)
respond_to do |format|
if @reservation.save
@saved_reservation = @reservation
format.html { redirect_to :back, notice: 'Reservation was successfully created.' }
format.json { render :show, status: :created, location: @reservation }
ReservationMailer.fresh_message(@saved_reservation, @email).deliver_now
else
format.html {redirect_to :back
flash[:info] = @reservation.errors.full_messages do |m|
m
end}
format.json { render json: @reservation.errors, status: :unprocessable_entity }
end
end
end
但我无法看到任何验证错误,即使是在线状态:真实。 好像我没有正确的@reservation,因为我在form_for中处理过Array。请帮我解决这个问题,谢谢!
答案 0 :(得分:1)
您没有看到验证错误的原因是因为您在验证失败而不是渲染时发出redirect_to :back
:新操作已包含您在@reservation实例对象中可能出现的任何错误。
此外,您尝试在尝试使用@reservation对象显示错误消息时将错误消息添加到Flash消息中。
这应该是正确的else
条款
else
format.html { render :new }
format.json { render json: @reservation.errors, status: :unprocessable_entity }
end