How do I combine two methods into one json formatted variable?
I'm storing JSON formatted data into a var adds with the following methods:
var adds = <%= raw @add.to_a.to_json %>;
var adds = <%= raw @add.nearbys(1).to_json %>;
The first line of code stores the location of an individual in JSON format, the second line of code searches for that person's neighbors, within a 1 mile range. How do I combine both of these lines of code 开发者_开发百科and store the data in JSON format in the var adds variable?
If you are interested in source, its here. The location is layout/adds.html.erb
I'm not sure why it's so important to have both pieces of data in one adds variable (can you simply do var adds and thenvar addNearbys?), but
var adds = {
all: <%= raw @add.to_a.to_json %>,
nearbys: <%= raw @add.nearbys(1).to_json %>
};
would get you all the data in one variable, in JSON.
Alternatively, you could do
var adds = <%= {:all => @add.to_a, :nearby => @add.nearbys(1)}.to_json %>
but that takes more processing because you'd be initializing a Hash.
This was recently a huge issue for me and the solution is actually very elegant.
Note: be wary of the to_json solutions for aggregating JSON strings.
See my question here
加载中,请稍侯......
精彩评论