I am using gmaps4rails with Rails 3.0.9. I would like to add a marker based on the latitude and longitude coordinates to the map, but I can't figure out how should I do it. I managed to use the map with an andress only. Thanks.
The code I'm using:
app/models/location.rb
class Location < ActiveRecord::Base
acts_as_gmappable :process_geocoding => false
def gmaps4rails_address
"#{self.latitude}, #{self.longitude}"
end
end
app/controllers/locations_controller.rb
def index
#json = Location.first.to_gmaps4rails
respond_to do |format|
format.html
end
app/views/locations/index.html.erb
<%= gmaps4rails(#json) %>
The location model contains the following fields: latitude, longitude, address.
UPDATE: I found the solution after reading one more time project's wiki about markers. The solution is to use custom <%= gmaps %> method. I managed to use it like this:
<%= gmaps({
"map_options" => { "type" => "ROADMAP", "center_longitude" => 28.9, "center_latitude" => 47.03, "zoom" => 12, "auto_adjust" => true},
"markers" => { "data" => #markers }
})
%>
In the controller:
#markers = '[
{"description": "", "title": "", "sidebar": "", "lng": "28.8701", "lat": "47.0345", "picture": "", "width": "", "height": ""},
{"lng": "28.9", "lat": "47" }
]'
You can customize these values as you like.
I think you should try geocoder gem instead of gmaps4rails
https://github.com/alexreisner/geocoder
http://www.rubygeocoder.com/
I think it is much better than gmaps4rails
Related
I am developing in student tracking website in RoR. In model I have following code to build json
self.as_json
json = Jbuilder.new do |j|
j.courses student_courses do |course|
j.(course, :id, :name)
j.students students, :name
end
end.target!
puts json
return json
end
My controller code is
render json: {
courses: course.as_json,
}
and produces
{"courses":[
"{\"id\": 1,\"name\": \"english\",\"students\": [{\"name\": \"ALison\"},{\"name\": \"Robert\"}]
},{...}... ]"
instead of
"courses" : [
{
"id": 1,
"name": "english",
"students": [
{"name": "ALison"},
{"name": "Robert"}]
}, {..},...
]
It is adding escape character(/) before every double quotes. How can I solve this issue
Hey you can use this to generate as alternative
course.to_json(:include => { :students => { :only => :name } })
I am having trouble trying to render specific fields in my rails app my structure is like so:
Home_controller.rb
def index
taobao_hash = OpenTaobao.get(
:method => "taobao.tbk.item.get",
:fields => "num_iid,title,nick,pict_url,cid,price,type,delist_time,post_fee,score,volume",
:q => "snus",
:page_size => 1,
:sort => "_des",
)
h = JSON.parse(taobao_hash.to_json)
render json: h["tbk_item_get_response"]
end
How this renders my whole request as json like so
{
"results": {
"n_tbk_item": [
{
"nick": "恶毒对于",
"num_iid": 17707525948,
"pict_url": "http://img4.tbcdn.cn/tfscom/i2/TB1umhOHVXXXXa0aXXXXXXXXXXX_!!0-item_pic.jpg",
"title": "瑞典戒烟产品唇烟嚼烟经典款General Classic White Portion Snus",
"volume": 127
}
]
},
"total_results": 99,
"request_id": "1476rjvn5sc2g"
}
How would I go about only rendering title in my view? I can only seem to render everything.
I'm witnessing an odd behavior in Rails, when sending a post request, with the following body:
If you check is a Hash (converted to JSON when sending). But ODDLY when being read by params in controller, is recognized like this:
If you check carefully, the attributes of :first_name and :email are moved to the previous item in the array.
I'd thought if you have an array with certain attributes on the first item, but some different attributes on the following items, the array would be respecting the positions of which the attributes are set for.
I know most likely the answer would be "just put a nil or empty value of those attributes on the first item of the array", but I'm more interested in the reason of why this is happening.
Thank you.
UPDATE
Thanks to a question, I replicated the scenario form a browser (I was originally doing the request from the test feature of rails), and checking the Network from the browser, this is what is being sent:
{
"name": "un nombre",
"team_members": [
{
"user_id": 1,
"team_member_role_id": 4
},
{
"email": "cpamerica#avengers.com",
"first_name": "Cap America",
"team_member_role_id": 4,
"admin": true
},
{
"email": "hulk#avenrgers.com",
"first_name": "Bruce Banner",
"team_member_role_id": 1,
"admin": false
},
{
"email": "ironman#avengers.com",
"first_name": "Tony Stark",
"team_member_role_id": 1,
"admin": false
},
{
"email": "thor#avengers.com",
"first_name": "Thor Hijo de Odín",
"team_member_role_id": 2,
"admin": false
}
]
}
And it works. So I focused on how I was sending the info from the test environment, this is the actual code:
team = {
:name => 'un nombre',
:team_members => [
{
:user_id => 1,
:team_member_role_id => TeamMemberRole.role_communicator_id
},
{
:email => 'cpamerica#avengers.com',
:first_name => 'Cap America',
:team_member_role_id => TeamMemberRole.role_communicator_id,
:admin => true
},
{
:email => 'hulk#avenrgers.com',
:first_name => 'Bruce Banner',
:team_member_role_id => TeamMemberRole.role_visionary_id,
:admin => false
},
{
:email => 'ironman#avengers.com',
:first_name => 'Tony Stark',
:team_member_role_id => TeamMemberRole.role_visionary_id,
:admin => false
},
{
:email => 'thor#avengers.com',
:first_name => 'Thor Hijo de Odín',
:team_member_role_id => TeamMemberRole.role_developer_id,
:admin => false
}
]
}
post create_team_path, :team => team, :format => :json
And what is being read in the controller by request.raw, this is what is getting (using the debugger):
team[name]=un+nombre&
team[team_members][][user_id]=1&
team[team_members][][team_member_role_id]=4&
team[team_members][][email]=cpamerica%40avengers.com&
team[team_members][][first_name]=Cap+America&
team[team_members][][team_member_role_id]=4&
team[team_members][][admin]=true&
team[team_members][][email]=hulk%40avenrgers.com&
team[team_members][][first_name]=Bruce+Banner&
team[team_members][][team_member_role_id]=1&
team[team_members][][admin]=false&
team[team_members][][email]=ironman%40avengers.com&
team[team_members][][first_name]=Tony+Stark&
team[team_members][][team_member_role_id]=1&
team[team_members][][admin]=false&
team[team_members][][email]=thor%40avengers.com&
team[team_members][][first_name]=Thor+Hijo+de+Od%C3%ADn&
team[team_members][][team_member_role_id]=2&
team[team_members][][admin]=false&
format=json
Any idea on why the index of each team_member is missing? Am I sending the array wrong?
To send an acceptable json request you need to send as a formed String instead the hash, also add the headers
your code must look something like this:
post create_team_path, {:team => team}.to_json, 'CONTENT_TYPE' => 'application/json;charset=utf-8'
Note the problem is within the parser hash to form-request not adding the index of each object
Source: How to post JSON data in rails 3 functional test
We've got a simple api endpoint that works like so:
def index
render json: Country.all
end
This is unfortunately giving us this output:
{
"countries" => [
[0] {
"countries" => {
"id" => 1,
"iso" => "US",
"iso3" => "USA",
"iso_name" => "UNITED STATES",
"name" => "United States of Foo",
"numcode" => 840
}
},
[1] {
"countries" => {
"id" => 2,
"iso" => "CA",
"iso3" => "CAN",
"iso_name" => "CANADA",
"name" => "Canada",
"numcode" => 124
}
}
]
}
Notice that the key for each individual object is the plural form of the key.
However, when we set the endpoint to work like so
def inded
render json: {countries: Country.all}
end
The output looks like so:
{
"countries" => [
[0] {
"country" => {
"id" => 1,
"iso" => "US",
"iso3" => "USA",
"iso_name" => "UNITED STATES",
"name" => "United States of Foo",
"numcode" => 840
}
},
[1] {
"country" => {
"id" => 2,
"iso" => "CA",
"iso3" => "CAN",
"iso_name" => "CANADA",
"name" => "Canada",
"numcode" => 124
}
}
]
}
I.e., correct.
However, setting the key like {countries: Country.all} is bad form, and I'd like to understand why rails is serializing each element with the collection key rather than the object key (that is, why it's plural and not singular for each country).
We have not overridden to_json or any other serialization methods. We are using the default rails model serializer (I tried making an explicit serializer, but there was no change in behavior). I cannot, for the life of me, figure out why it is pluralizing these keys.
Edit: There is even more weirdness. I was incorrect about the explicit serializer, when I set up a serializer (with just the attributes as it normally displays), I get this:
{
"countries" => [
[0] {
"id" => 1,
"iso" => "US",
"iso3" => "USA",
"iso_name" => "UNITED STATES",
"name" => "United States of Foo",
"numcode" => 840
},
[1] {
"countries" => {
"id" => 2,
"iso" => "CA",
"iso3" => "CAN",
"iso_name" => "CANADA",
"name" => "Canada",
"numcode" => 124
}
}
]
}
The first object has no key, and every other one is plural. I tested both in tests, and confirmed by making the actual API call.
I can't find anything that would override this other than an overridden <=> and to_s. These should not affect output in this way?
Mike, I think you copied and pasted something wrong, or you might just be confused.
Both outputs have the same results: Countries (Plural) as the main response, and country(Singular) for each individual inside countries. Or am I misreading?
I think what's happening here is that you're trying to specify the root key in a way that AM::S doesn't support.
Instead of render json: { countries: Country.all }, I'd recommend trying render json: Country.all, root: "countries" (specifying the root key is unnecessary if you're calling the serializer from within CountriesController, otherwise you need it to get the functionality you desire).
See https://github.com/rails-api/active_model_serializers/tree/0-8-stable#arrays for more information.
Here is the example from the crack documentation:
json = '{"posts":[{"title":"Foobar"}, {"title":"Another"}]}'
Crack::JSON.parse(json)
=> {"posts"=>[{"title"=>"Foobar"}, {"title"=>"Another"}]}
But how do I actually access the data in the hash?
I've tried the following:
array = Crack::JSON.parse(json)
array["posts"]
array["posts"] shows all the values, but I tried array["posts"]["title"] and it didn't work.
Here is what I am trying to parse as an example:
{"companies"=>[{"city"=>"San Mateo", "name"=>"Jigsaw", "address"=>"777 Mariners Island Blvd Ste 400", "zip"=>"94404-5059", "country"=>"USA", "companyId"=>4427170, "activeContacts"=>168, "graveyarded"=>false, "state"=>"CA"}], "totalHits"=>1}
I want to access the individual elements under companies....like city and name.
Like this?
hash = {
"companies" => [
{
"city" => "San Mateo",
"name" => "Jigsaw",
"address" => "777 Mariners Island Blvd Ste 400",
"zip" => "94404-5059",
"country" => "USA",
"companyId" => 4427170,
"activeContacts" => 168,
"graveyarded" => false,
"state" => "CA"
}
],
"totalHits" => 1
}
hash['companies'].each{ |i|
puts "city => #{i['city']}"
puts "name => #{i['name']}"
}
# >> city => San Mateo
# >> name => Jigsaw
hash['companies'][0]['city'] # => "San Mateo"
hash['companies'][0]['name'] # => "Jigsaw"
The problem is you didn't account for the array that companies points to.