如何在form_withRails中显示错误



我正试图在form_with中显示错误。这是我的代码:

预订/new.html.erb

(...)
<%= form_with(model: [@space, @booking], local: true) do |f| %>
<%= label_tag :check_in, "Check in" %>
<%= f.date_field :check_in, class: "form-control" %>
<%= label_tag :check_out, "Check out" %>
<%= f.date_field :check_out, class: "form-control" %>
<%= submit_tag "Reserve", class: "btn btn-primary %>
<% end %>
(...)

这是控制器:

bookings_controller.rb

(...)
def new
@space = Space.find(params[:space_id])
@booking = Booking.new
@query1 = session[:query1]
@query2 = session[:query2]
end
def create
@space = Space.find(params[:space_id])
booking  = Booking.create(booking_params)
unless booking.valid?
#show your errors
redirect_to new_space_booking_path(@space)
else
session = Stripe::Checkout::Session.create(
payment_method_types: ['card'],
line_items: [{
(...)
}],
success_url: success_booking_payments_url(booking),
cancel_url: new_booking_payment_url(booking)
)
booking.update_attribute(:checkout_session_id, session.id)
redirect_to new_booking_payment_path(booking)
end
end

private
def booking_params
params.require(:booking).permit(:check_in, :check_out).merge(state: 'pending', amount: @space.price, user: current_user, space: @space)
end
end

一切都很好,但我想在表单中显示错误(字段和基(。我尝试了一些解决方案,比如Rails form_with-errors(remote:true(,但在我的情况下似乎不起作用。

create!抛出错误,create没有。

可能想要这样的东西。

class BookingsController < ApplicationController
def new
@space = Space.find(params[:space_id])
@booking = Booking.new
@query1 = session[:query1]
@query2 = session[:query2]
end
def create
@space = Space.find(params[:space_id])
@booking  = Booking.new(booking_params)
if @booking.save
session = Stripe::Checkout::Session.create(
payment_method_types: ['card'],
line_items: [{
name: @space.address,
images: [@space.photo],
amount: @space.price_cents * (1 + (@booking.check_out - @booking.check_in).to_i),
currency: 'gbp',
quantity: 1
}],
success_url: success_booking_payments_url(@booking),
cancel_url: new_booking_payment_url(@booking)
)
@booking.update_attribute(:checkout_session_id, session.id)
redirect_to new_booking_payment_path(@booking)
else
render :new
end
end
private
def booking_params
params.require(:booking).permit(:check_in, :check_out).merge(state: 'pending', amount: @space.price, user: current_user, space: @space)
end
end

相关内容

  • 没有找到相关文章

最新更新