0

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?

9
  • Keep a dropdown or select option , what's stopping you . You can use jquery to stop multiple selection on radio buttons . Commented 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 right Commented 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. Commented 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 model Commented Oct 30, 2014 at 6:26
  • Thanks @CaffeineCoder I comfortable with Rails validation just wanting to know if my above question is possible. Commented Oct 30, 2014 at 6:30

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for such a wonderful, well informed and articulate answer. I see what you mean with the column names / model attributes I will rewrite this to reflect your answer. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.