[英]Conditional Rails Form Validation
I have a rails model that has two field attributes: :commission_fixed
& :commission_percentage
. 我有一个具有两个字段属性的rails模型:commission_fixed
和:commission_percentage
。 The user should only be able to choose between one of the two options either: :commission_fixed
or :commission_percentage
not both on form submit. 用户只能在以下两个选项之一中进行选择:commission_fixed
或:commission_percentage
不能同时在表单提交中选择。 Is this possible using Rails validation? 使用Rails验证可以吗? If so what is the best way to achieve this? 如果是这样,实现此目标的最佳方法是什么?
Your problem is within the way you've structured your column names / model attributes. 问题在于结构化列名/模型属性的方式。
Ideally you should change your attribute names on your model to :commission_method
and :commission_rate
. 理想情况下,您应该将模型上的属性名称更改为:commission_method
和:commission_rate
。 This allows for greater flexibility. 这允许更大的灵活性。 Then in your view you can achieve what you're looking for with a radio button. 然后,在您的视图中,您可以通过单选按钮实现所需的功能。 You can store your :commission_rate
as a decimal in the db. 您可以将:commission_rate
以小数形式存储在数据库中。
<%= f.radio_button :commission_method, "Fixed" %>
<%= f.radio_button :commission_method, "Percentage" %>
<%= f.number_field :commission_rate %>
In your view files if you need to switch between showing a fixed amount and a percentage you can just do: 在视图文件中,如果需要在显示固定金额和百分比之间进行切换,可以执行以下操作:
<% case @sales_associate.commission_method %>
<% when 'Fixed' %>
<span>Fixed: <%= number_to_currency(@sales_associate.commission_rate) %></span>
<% when 'Percentage' %>
<span>Percentage: <%= "% #{@sales_associate.commission_rate}" %></span>
<% end %>
However, you "could" write a custom validation method that throws an error if both attributes were assigned. 但是,您“可以”编写一个自定义验证方法,如果同时分配了两个属性,则该方法将引发错误。
In whatever model: 在任何模型中:
class SalesAssociate
validate :only_one_selected_commission
def only_one_selected_commission
errors[:base] << "Please select only one form of commission" if self.commission_fixed.present? && self.commission_percentage.present?
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.