简体   繁体   中英

Custom setter method won't accept blank values in Ruby on Rails?

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM