我有一个隐藏字段的表单,它从参数中获取值。当我第一次进入表单页面时,我的网址看起来像这样:
http://localhost:3000/requests/new?parent_request_id=1&patient_id=1
所以我有parent_request_id和patient_id参数。而我的hidden_fields获得了这些值。
当用户提交表单时,如果未通过验证,则用户将返回到包含错误消息的同一页面。问题是url中的那些参数消失,因此隐藏的字段为空。
如何保存这些参数。或者有更好的方法在视图之间发送变量吗?
编辑: 我的控制器代码:
# requests_controller.rb
# POST /requests
# POST /requests.json
def create
@request = Request.new(request_params)
respond_to do |format|
if @request.save
format.html { redirect_to @request, notice: 'Request was successfully created.' }
format.json { render :show, status: :created, location: @request }
else
format.html { render :new }
format.json { render json: @request.errors, status: :unprocessable_entity }
end
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def request_params
params.require(:request).permit(:description, :diagnos, :payed, :price, :doctor_id, :patient_id, :parent_request_id)
end
和我的表格:
<div class="form">
<h1>Данные по обращению</h1>
<%= form_for(@request) do |f| %>
<%= render 'layouts/error_messages', object: @request %>
<%= f.hidden_field :parent_request_id, value: params[:parent_request_id] %>
<%= f.hidden_field :patient_id, value: params[:patient_id] %>
<% if can? :manage, :all %>
<div class="field">
<%= f.label 'Лечащий врач' %>
<%= f.collection_select(:doctor_id, User.where(role:'doctor'),:id,:name,{include_blank:'-не выбрано-'}, class:'select2') %>
</div><br>
<% end %>
<div class="field">
<%= f.label 'Описание' %><br>
<%= f.text_field :description %>
</div>
<div class="field">
<%= f.label 'Первичный диагноз' %><br>
<%= f.text_field :diagnos %>
</div>
<div class="field">
<%= f.label 'Стоимость' %><br>
<%= f.number_field :price %>
</div>
<div class="actions">
<%= f.submit 'Добавить данные', class:'button tiny' %>
</div>
<% end %>
</div>
答案 0 :(得分:2)
如果您在控制器中执行此操作
class RequestsController
def new
@request = Request.new(parent_request_id: params[:parent_request_id],
patient_id: params[:patient_id])
end
def create
@request = Request.new(request_params)
respond_to do |format|
if @request.save
format.html { redirect_to @request, notice: 'Request was successfully created.' }
format.json { render :show, status: :created, location: @request }
else
format.html { render :new }
format.json { render json: @request.errors, status: :unprocessable_entity }
end
end
end
end
简单地将您的观点视为
<%= form_for(@request) do |f| %>
<%= render 'layouts/error_messages', object: @request %>
<%= f.hidden_field :parent_request_id %>
<%= f.hidden_field :patient_id %>
<% end %>
您将在新操作中将属性绑定到请求对象,因此如果验证失败并且不会将其设置为nil的参数,它们将会存在。