2014-10-30 30 views
0

我有一个轨道模型,有两个字段属性::commission_fixed & :commission_percentage。用户应该只能选择以下两个选项之一::commission_fixed:commission_percentage不能同时在表单提交。这可能使用Rails验证?如果是这样的话,最好的办法是什么?有条件的轨道窗体验证

+0

保持一个下拉菜单或选择选项,是什么阻止你。您可以使用jquery停止单选按钮上的多项选择。 – 2014-10-30 06:14:09

+0

@CaffeineCoder我们怎样才能使两个属性的选择框,这是可能的AFAIK我们可以发送选项作为选择框单一属性 – anusha 2014-10-30 06:15:27

+0

感谢您的答复。我知道我可以通过这种方式来实现,我的问题更多是出于好奇,如果可以纯粹通过使用Rails验证来实现。 – 2014-10-30 06:17:18

回答

0

您的问题在于您构建了列名称/模型属性的方式。

理想情况下,您应该将模型上的属性名称更改为:commission_method:commission_rate。这允许更大的灵活性。然后在您的视图中,您可以使用单选按钮实现您要查找的内容。您可以将:commission_rate作为小数点存储在数据库中。

<%= f.radio_button :commission_method, "Fixed" %> 
<%= f.radio_button :commission_method, "Percentage" %> 
<%= f.number_field :commission_rate %> 

在视图文件,如果你需要显示一个固定的量和比例,你可以切换只是做:

<% 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 %> 

但是,“可能”写的是抛出一个自定义的验证方法如果两个属性都已分配,则会出错

在任何型号:

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 
+0

谢谢你这样一个美好的,充分知情和清晰的答案。我明白你的意思与列名/模型属性,我会重写这个来反映你的答案。欢呼 – 2014-10-31 00:11:31

+0

很高兴提供帮助。干杯 – 2014-10-31 00:52:52