Preserving Data on Rails Migration with Override on Getter/Setter -
i'm doing migration need both (a) change column's data type , (b) preserve data in column (ie, convert new data type , keep in same column). new column type requires me override getters , setters , causes migration fail.
there user table includes field ip address of user's connection: ip_addr. string , want change integer. up method of migration looks this:
def   add_column :users, :curip, :integer   user.reset_column_information   user.all.each |u|     u.update_attribute :curip, user.ip_str_to_int(u.ip_addr)   end   remove_column :users, :ip_addr   rename_column :users, :curip, :ip_addr end   (user.ip_str_to_int math convert ip address quads integer.)
i have methods override getter & setter ip_addr call user.ip_str_to_int , corresponding method user.ip_int_to_str. these methods this:
def ip_addr   val = read_attribute(:ip_addr)   user.ip_int_to_str(val) end  def ip_addr=(val)   write_attribute(:ip_addr, user.ip_str_to_int(val)) end   by you've guessed problem. when migration runs, chokes, because overridden getter/setters expect column contain integer, @ time migration happens, column contains string. i've tested migration , getter/setter methods separately, , they're fine. own development environment, can comment out getters/setters run migration, put them in. kludge , doesn't work production.
any suggestions? know wouldn't have problem if wasn't trying keep same column name, changing column name means changing other code.
environment: sqlite 3; ruby 2.1.4; rails 3.2.13.
you modify getter method handle case of data being string...
def ip_addr   val = read_attribute(:ip_addr)   return val if val.is_a? string   user.ip_int_to_str(val) end      
Comments
Post a Comment