如果位置设置为Deployed,我试图让POC字段成为必填字段,但如果设置为Local,则不是。我试过这个:
<%= form_with(model: hardware, local: true, multipart: true) do |form| %>
<% if hardware.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(hardware.errors.count, "error") %> prohibited this hardware from being saved:</h2>
<ul>
<% hardware.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label "Location" %>
<%= form.select :location, ['Local', 'Deployed'] %>
</div>
<div class="field">
<%= form.label "POC" %>
<% if (:location == 'Deployed')%>
<%= form.collection_select(:poc_id, Poc.all, :id, :name, { :prompt => 'Select a POC', :selected => @hardware.poc_id, include_blank: true }, { class: 'form-control', required: true }) %>
<% else %>
<%= form.collection_select(:poc_id, Poc.all, :id, :name, { :prompt => 'Select a POC', :selected => @hardware.poc_id, include_blank: true }, { class: 'form-control' }) %>
<% end %>
</div>
当我像这样运行它时,它不会给出任何错误,但不需要该字段。两个集合选择之间的唯一区别是在最后我为if语句设置了required:true标志,并在else语句中将其关闭。
有没有办法用我正在尝试的方法做到这一点?是否有任何Ruby表单助手可以使用该功能?我是否需要使用Javascript来实现此功能?