验证另一个字段是否大于

时间:2016-05-01 23:36:48

标签: ruby-on-rails validation

<tr>
    <td>Bill:</td>
    <td colspan="2"><%= select_tag 'bill_hours', options_for_select(@hours, 0)  %>:<%= select_tag 'bill_minutes', options_for_select(@minutes, 0)  %></td>
  </tr>
  <tr>
    <td>Nonbill:</td>
    <td colspan="2"><%= select_tag 'nonbill_hours', options_for_select(@hours, 0)  %>:<%= select_tag 'nonbill_minutes', options_for_select(@minutes, 0)  %></td>
  </tr>
  <tr>
    <td>Category:</td>
    <td colspan="2">
     <%=select_tag 'cat_type_id',options_for_select(@cat_type_list,@selected_cat_type), {:prompt=>"Select Category Type"}%><br/>
      <select id="activity_category_id" prompt="Select Category" name="activity[category_id]" style="width:300px;">
        <option value=''>Select Category</option>
        <%@cat_list.each do |c|%>
        <option value="<%=c.id%>" <%=(!@activity.nil? && @activity.category_id==c.id) ? "selected" : "" %> class="<%=c.cat_type_id.nil? ? '':c.cat_type_id%>"><%=c.short_description.nil? ? c.description : c.short_description%></option>
        <%end%>
      </select></td>
  </tr>
  <tr>
    <td>Location:</td>
    <td colspan="2"><%=select 'activity', 'location_id', @locations, {:prompt=>"Select Location"}, :required => true %><br/><%=select 'activity', 'location_modifier_id', @location_mods, {:prompt=>"Select Modifier"}, :required => true %></td>
  </tr>

我将上面的代码作为样本。如果且仅当"activity, location_id""bill_hours""bill_minutes""nonbill_hours"为&gt;时,如何才能"nonbill_minutes"为必填项? 0?

1 个答案:

答案 0 :(得分:1)

传递:if密钥以使用验证条件。

在您的模型中:

validates_presence_of :location_id, if: -> do 
  %i(bill_hours bill_minutes nonbill_minutes nonbill_hours).any? { |attr| read_attribute(attr) > 0 } 
end