我使用的form_for遠程:真正在我和幾個驗證視圖,它觸發JS響應部分追加到一個div:的Rails的form_for部分呈現兩種驗證失敗,正確的驗證
的index.html .erb
<%= bootstrap_form_for @reservation, html: { id: "createReservationForm", method: :post }, remote: true do |f| %>
<div id="error_div"></div>
<%= f.datetime_select :start_time, ampm: true, discard_minute: true, :minute_step => 60 %>
<%= f.select :party_size, (1..6).map { |i| [i,i] } %>
<%= f.text_field :name, required: true %>
<%= f.hidden_field :restaurant_id, value: @restaurant.id %>
<%= f.submit 'Create Reservation', id: "formSubmit" %>
<% end %>
reservations_controller.rb
def create
@reservation = Reservation.new(reservation_params)
@reservation.start_time = @reservation.start_time.beginning_of_hour
@reservation.end_time = @reservation.start_time + 1.hour
respond_to do |format|
if @reservation.save
format.html { render action: 'index' }
format.js { render action: 'create', status: :created, location: @reservation }
else
format.html { render action: 'index' }
format.js { render action: 'create', status: :unprocessable_entity, errors: @reservation.errors.full_messages }
end
end
end
reservation.rb
validates :start_time, presence: true
validates :name, presence: true
validates :party_size, presence: true
validate :not_past
def not_past
if start_time.past?
errors.add :start_time, "cannot be in past"
end
end
create.js.erb
$("#createReservationForm").on("ajax:success", function(e, data, status, xhr) {
$("#error_div").html('');
$("#reservationList").prepend("<%= j render partial: 'reservation', locals: { reservation: @reservation } %>")
$("#createReservationForm")[0].reset();
return false;
}).on("ajax:error", function(e, xhr, status, error) {
$("#error_div").html("<%= j render partial: 'shared/error_messages', locals: { object: @reservation } %>")
return false;
});
我遇到的問題是,當我說,提交失敗「not_past」驗證,我得到錯誤信息,並沒有提交表單。然後,當我調整表單上的時間以使其通過'not_past'驗證時,它會追加新的@reservation以及之前提交的未通過驗證的驗證。有沒有辦法以某種方式「清除」前一個失敗的問題,以便當用戶調整表單上的時間以通過驗證時,它只會追加該版本?
我試着搞錯'返回錯誤',我試過在創建一個新的控制器之前將@reservation設置爲零,我也沒有在respond_to塊中放置「@reservation」,它只是給了我一個正確的,所以我不確定不正確的那個在哪裏。