Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-3.2

Rails Convert date_select to an int value


In Rails 3.x I have a model class with an int field "my_int_date". I would like the int field to be populated by a form which as a date_select form element.

The problem is when the form reads a date_select value it sends it back as a multi-parameter value which results in the error

1 error(s) on assignment of multiparameter attributes

Is there anyway I can keep it stored as a Date in my model but convert it to an int when it is dumped to the DB?


Solution

  • Heres how I solved it,

    In my ActiveRecord model I added the fields

    attr_accessible :my_int_date_time
    
    columns_hash["my_int_date_time"] = ActiveRecord::ConnectionAdapters::Column.new("my_int_date_time", nil, "DateTime")
    
    def my_int_date_time
      return TimeHelper.datetime_from_integer(self.my_int_date)
    end
    
    def my_int_date_time= val
        self.my_int_date = TimeHelper.datetime_to_integer(val)
    end
    

    In my form I then linked the datetime field to the field my_int_date_time rather than linking it to my_int_date