I have a CommercialDocument model which have a discount_amount attribute and a discount_amount_with_tax virtual attribute.
Here is how I defined this in my model :
def discount_amount_with_tax
discount_amount * (1 + tax.rate / 100)
end
def discount_amount_with_tax=(amount)
self.discount_amount = amount.to_f / (1 + tax.rate / 100)
end
In my form, a user can fill in both discount_amount and discount_amount_tax :
= f.label :discount_amount
= f.text_field :discount_amount
= f.text_field :discount_amount_with_tax
I want to give the priority to the discount_amount_with_tax field, which means that discount_amount must not be taken into account unless the other field is empty.
My problem is that if I put nothing in the discount_amount_with_tax field, and let’s say 10 in discount_amount, then discount_amount will be equal to 0, which is clearly not what I want.
How can I fix this ?
Any help would be greatly appreciated.
A blank string converts to a zero integer. Therefore:
During mass-assignment,
discount_amount_with_tax=is called. A blank form input is passed as an empty string, which Active Record then converts to an integer (zero).discount_amount_with_tax=setsdiscount_amountto zero regardless ofdiscount_amount‘s previous value.Easy way around this is to use a conditional:
Mind you, this is the easy way, not the ideal way. A better solution is to write custom setter logic in the controller in lieu of mass-assignment; basically to manually set these attributes in the controller.