Custom setter method won't accept blank values in Ruby on Rails? -
i have class:
class project < activerecord::base attr_accessible :hourly_rate validates :hourly_rate, :numericality => { :greater_than => 0 }, :allow_blank => true, :allow_nil => true def hourly_rate read_attribute(:hourly_rate_in_cents) / 100 end def hourly_rate=(number) write_attribute(:hourly_rate_in_cents, number.to_d * 100) end end the problem setter method doesn't behave in way want it.
in form, when leave hourly_rate input field blank , hit update, 0 appears in input field again if magic , validation error: hourly rate must greater 0
can tell me i'm missing here? want field optional.
thanks help!
i imagine problem if leave field blank, params[:project][:hourly_rate] "". if @project.hourly_rate = "" @project.hourly_rate 0, not nil.
this because "".to_d 0. therefore write_attribute(:hourly_rate_in_cents, number.to_d * 100) write value 0 when number "".
def hourly_rate=(number) hourly_rate_value = number.present? ? number.to_d * 100 : nil write_attribute(:hourly_rate_in_cents, hourly_rate_value) end should fix this.
Comments
Post a Comment