検証エラーが奇数回の試行でのみ表示されるのはなぜですか?
概要
このビューhtml.erbがあります
<h1>Edit</h1>
<%= render "form", appointment: @appointment, from: @source %>
<div>
<% if params[:source] == "confirmed" %>
<%= link_to "Volver atras", confirmed_path %>
<% elsif params[:source] == "request" %>
<%= link_to "Volver atras", requests_path %>
<% elsif params[:source] == "user" %>
<%= link_to "Volver atras", @appointment %> |
<% end %>
</div>
形式は次のとおりです。
<%= form_with(model: appointment) do |form| %>
<% if appointment.errors.any? %>
<div style="color: red">
<h2> Tu turno tiene <%= appointment.errors.count %> error/es:</h2>
<ul>
<% appointment.errors.each do |error| %>
<li><%= error.full_message.split(" ")[1..].join(" ") %></li>
<% end %>
</ul>
</div>
<% end %>
<div>
<%= form.label :time, style: "display: block" %>
<%= form.datetime_field :time%>
</div>
<div>
<%= form.hidden_field :source, value: @from %>
<%= form.submit %>
</div>
<% end %>
そして私のアポイントコントローラー:
def update
respond_to do |format|
ant= @appointment.state
if params[:appointment][:source] == "request"
@appointment.state= 3
if @appointment.update(appointment_params)
format.html { redirect_to requests_path, notice: "Turno actualizado, espere la confirmación." }
format.json { render :show, status: :ok, location: @appointment }
else
@appointment.state= ant
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @appointment.errors, status: :unprocessable_entity }
end
end
end
したがって、ビュー内で無効な時間を選択すると、警告するエラーが表示されます。問題は、2 回目に間違えると、警告は表示されず、時間フィールドはその時間にリセットされます。私は以前に経験しました(これは最初は発生せず、画面にエラーが表示されても継続します)。 3回目はうまくいきましたが、4回目はまた同じことが起こりました
Ruby on Rails は初めてなので、何をすればよいのかよくわかりませんでした
解決策
編集アクションで @source の値を設定してください。
更新が失敗すると、「編集」ビューが表示され、編集アクションのコードは実行されません。
したがって、フォームが送信されてエラーが発生した後に @source の値を設定することもできます。
else
@appointment.state= ant
# set value for @source here, ex:
@source = params[:appointment][:source]
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @appointment.errors, status: :unprocessable_entity }
end