Reputation: 10207
I have this 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 is that my setter method doesn't behave in the way I want it.
In my form, when I leave the hourly_rate
input field blank and then hit Update
, a 0
appears in the input field again as if by magic and I get a validation error: Hourly rate must be greater than 0
Can anybody tell me what I'm missing here? I want that field to be optional.
Thanks for any help!
Upvotes: 1
Views: 414
Reputation: 1390
I imagine the problem is that if you leave the field blank, params[:project][:hourly_rate]
will be ""
. If you do @project.hourly_rate = ""
then @project.hourly_rate
will be 0
, not nil.
This is because "".to_d
is 0
. Therefore write_attribute(:hourly_rate_in_cents, number.to_d * 100)
will write the value 0
when number
is ""
.
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.
Upvotes: 2
Reputation: 1399
Your problem is this condition in your model:
validates :hourly_rate, :numericality => { :greater_than => 0 }.
You're telling it to be greater than 0. Either provide input > 0 or comment out that line with "#" in front of it.
When you first did the migration, it put those conditions in so now undo that as follows.
rails g migration remove_numericality_from_hourly_rate
Then in your migration file:
class RemoveNumericallityFromHourlyRate < ActiveRecord::Migration
def self.up
change_column :my_table, :hourly_rate, :string
end
end
Then run this: run rake db:migrate
Upvotes: 0