简体   繁体   中英

Object with BigDecimals returns empty strings on to_s

I have a location table I use to store geo coordinates:

class Location < ActiveRecord::Base
  # Location has columns/attributes
  #   BigDecimal latitude
  #   BigDecimal longitude

  (...)

  def to_s
    @latitude.to_s << ', ' << @longitude.to_s
  end
end

However, when I call to_s on a Location, the BigDecimal inside converts to an empty string.

ruby > l
 => #<Location id: 1, latitude: #<BigDecimal:b03edcc,'0.4713577E2',12(12)>, longitude: #<BigDecimal:b03ecb4,'-0.7412786E2',12(12)>, created_at: "2011-08-06 03:41:51", updated_at: "2011-08-06 22:21:48"> 
ruby > l.latitude
 => #<BigDecimal:b035fb0,'0.4713577E2',12(12)> 
ruby > l.latitude.to_s
 => "47.13577" 
ruby > l.to_s
 => ", " 

Any idea why?

Your to_s implementation is wrong, it should be this:

def to_s
    latitude.to_s << ', ' << longitude.to_s
end

ActiveRecord attributes are not the same as instance variables and accessing @latitude inside the object is not the same as accessing latitude inside the object, @latitude is an instance variable but latitude is a call to a method that ActiveRecord creates for you.

Also, instance variables auto-create as nil on first use so your original to_s was just doing this:

nil.to_s << ', ' << nil.to_s

and that isn't the result you're looking for.

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