RoR: Question about turning an array from a query into a string
Right now I am new to RoR, and just playing around with things to learn a bit about 开发者_JAVA技巧the language. I am currently trying to get zipcodes within a distance of another zip (from a local database).
I managed to work out:
def get_local_zipcodes(zipcode, distance)
@getLocalZipcodesZipHash = Zipcode.find(zipcode)
@getLocalZipcodesDistance = distance / 0.00062137119
@getLocalZipcodesZips = Zipcode.find(:all, :select => "id", :conditions => ["st_distance(ST_GeographyFromText(?), ST_GeographyFromText( geography)) < ?", @getLocalZipcodesZipHash.geography, @getLocalZipcodesDistance])
return @getLocalZipcodesZips
end
which may be a sloppy way of doing this. (suggestions on cleaning it up would be appreciated as well)
This returns about 30 results in the form of:
[#<Zipcode id: "23320">, #<Zipcode id: "23321">,...,#<Zipcode id: "23708">, #<Zipcode id: "23709">]
I'd like to turn the zipcodes in quotes into a comma separated string, and just ditch the rest of the text.
How would I do this?
--I've looked at the spatial adapter plugin before, but it didn't really look like what I was trying to do. It seems to use an api to get it's data.
Well for starters, you don't need to use instance variables if this is a model method and you won't be accessing them elsewhere. Second, there's not any real overhead to having an array of Zipcode objects instead of an array of equivalent String objects, so you don't need to worry about that.
I would recommend moving your distance ratio denominator (for lack of a better description) into a constant on the class.
class YourClass
DistanceRatio = 0.00062137119
def get_local_zipcodes(zipcode, distance)
zipcode = Zipcode.find(zipcode)
distance /= DistanceRatio
Zipcode.find(...)
end
end
You don't need that return
, either. Ruby methods return the result of the last statement automatically.
If you want an array of strings for some reason, you can easily get them from this statement like this:
get_local_zipcodes(zipcode, distance).map(&:id) #=> ['23320', '23321', ...]
If you provided a more information on what the context of this method is and what the various Zipcode methods do, I could be more specific on how you could refactor this.
精彩评论