Ruby on Rails Wednesday, February 1, 2012

This would be my solution:

lib/formatted_date_time.rb:

class ActiveRecord::Base
  
  def self.formatted_date_accessor(*names)
    names.each do |name|
      define_method("#{name}=") do |value|
        super(value)
        if value.present? && self[name].nil?
          class_eval do
            define_method name.to_sym do
              value
            end
          end
          self.class.validate do
            errors.add(name.to_sym, "can't be formatted")
          end
        end
      end
    end
  end
  
end


class User < ActiveRecord::Base
  formatted_date_accessor :birth_date

end

If you passing invalid date, it raises an validation error, but returns the invalid date to a form _at_request_.




On 01.02.2012, at 12:22, sandip ransing wrote:

consider scenario,

User model with name, birth_date fields (here birth_date is not mandatory field)

inside view form birth_date is assigned as '31/31/1985' which is invalid

ideally user object should be invalid and while save raise an error on birth_date field but that's not happening and user object gets saved with birth_date as blank which is completely misleading.

After debugging found that while assigning attributes birth_date value it gets assigned as blank and as birth_date is optional object gets saved.

class User < ActiveRecord::Base
 
def initialize(args={})
    logger
.info args[:birth_date] #invalid value comes upto here but vanishes afterwords
   
super
 
end
end

Any clue how to get validation working properly for not mandatory date fields ??


--
sαη∂ιρ Rαηѕιηg

---
www.funonrails.com

twitter, github @sandipransing


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment