I have a rails model that has two field attributes: :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. Is this possible using Rails validation? If so what is the best way to achieve this?
-
Keep a dropdown or select option , what's stopping you . You can use jquery to stop multiple selection on radio buttons .Caffeine Coder– Caffeine Coder2014-10-30 06:14:09 +00:00Commented Oct 30, 2014 at 6:14
-
@CaffeineCoder How can we make select box for two attributes, is it possible AFAIK We can send options to a single attribute as select box rightanusha– anusha2014-10-30 06:15:27 +00:00Commented Oct 30, 2014 at 6:15
-
Thanks for the response. I know I can achieve it this way, my questions was more out of curiosity and if it can be achieved purely through using Rails validation.Thomas Taylor– Thomas Taylor2014-10-30 06:17:18 +00:00Commented Oct 30, 2014 at 6:17
-
If you just want to validate a particular field , then you can do so by mentioning presence: true in the attribute modelCaffeine Coder– Caffeine Coder2014-10-30 06:26:49 +00:00Commented Oct 30, 2014 at 6:26
-
Thanks @CaffeineCoder I comfortable with Rails validation just wanting to know if my above question is possible.Thomas Taylor– Thomas Taylor2014-10-30 06:30:47 +00:00Commented Oct 30, 2014 at 6:30
1 Answer
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. 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.
<%= 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