Reputation: 19249
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?
Upvotes: 0
Views: 479
Reputation: 434585
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.
Upvotes: 3