开发者

Rails 3 validations problem

In my form I would like users to type a date in DD/MM/YYYY format. I have validation that checks that.

The problem is that in the database it is stored in YYYY-MM-DD format, so if try just to update the is_money_paid field:

job = Job.find(params[:id])
job.update_attributes(:is_money_paid => ...)

the validation fails saying that job's date is in wrong format (YYYY-MM-DD rather than DD/MM/YYYY).

What would be an appropriate way to solve this ?

Here is the relevant code:

class Job < ActiveRecord::Base
  validate :job_date_validator
end

DATE_REGEX = /\A\d{2}\/\d{2}\/\d{4}\z/

def job_date_validator
  if job开发者_如何学运维_date_before_type_cast.blank?
    errors.add(:job_date, "^Date must be selected")
  elsif job_date_before_type_cast !~ DATE_REGEX
    errors.add(:job_date, "^Date must be in DD/MM/YYYY format")
  end
end

is_money_paid is a boolean field.


I would change the validator to say:

validate_presence_of :job_date, :message => "must be selected"
validate :job_date_validator, :if => :job_date_changed?

Or something along those lines.

You can take out the .blank? check too.


Format it in before_validation

http://guides.rubyonrails.org/active_record_validations_callbacks.html#updating-an-object


I would suggest you to see gem validates_timeliness which is rails 3 compatible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜