LearningRoR
LearningRoR

Reputation: 27222

Price validation includes word "Free" if users put 0 or words in price field

How do i make it so if users put the number 0 or type any words in my price:decimal field it registers it as the word Free?

As of now i just validate presence of price:

validates :price,      :presence => true

Upvotes: 0

Views: 169

Answers (2)

Pablo Castellazzi
Pablo Castellazzi

Reputation: 4184

A simple way is to add a before_validation callback to do it.

class ModelWithPrice < ActiveRecord::Base
  # your validations ...

  before_validation :convert_price_to_number

private
  def convert_price_to_number
     # no need to check for strings, to_f return 0.0 if the value cant be converted
     self.price = self.price.to_f

     # convert 0 to "Free" if needed
     self.price = "Free" if self.price == 0
  end
end

Upvotes: 2

Max Williams
Max Williams

Reputation: 32945

I would have your field reference a new pair of get/set methods for "price_string"

#in your model
def price_string
  price == 0 ? "Free" : price
end

def price_string=(string)
  price = (string == "free" ? 0 : string)
end

Now you can refer to "price_string" in your forms.

#in your form
f.text_field :price_string

Upvotes: 2

Related Questions