RoR: JSON mapped :key => "value" – change all key names - ruby-on-rails

This is what I have:
def index
#attachments = current_user.attachments.all
respond_to do |format|
format.json do
render :json => #attachments.map { |o| { url: o.picture.thumb.url }}
end
end
end
=> [{:url=>"/uploads/attachment/picture/7/thumb_df3c0c3c.jpg"}, {:url=>"/uploads/attachment/picture/12/thumb_dd7839ee.jpg"}, ... }]
How can I change the key from :url to :thumb?
=> [{:thumb=>"/uploads/attachment/picture/7/thumb_df3c0c3c.jpg"},
{:thumb=>"/uploads/attachment/picture/12/thumb_dd7839ee.jpg"}, ... }]
This is the whole object after: render :json => #attachments
My goal: thumb: thumb: "/uploads/attach..."
Background: https://www.froala.com/wysiwyg-editor/docs/concepts/image-manager
I use the gem carrierwave to create a thumb

response.map! { |urls| { :thumb => urls[:url] } }

change key from "url" to "thumb"
render :json => #attachments.map { |o| { **thumb: o.picture.thumb.url** }}

Related

Build array from two hashes

I try to build json with geojson datas.
In my controller :
def index
....
respond_to do |format|
format.html
format.json { render json: { type: 'FeatureCollection', features: pois_geojson + tracks_geojson} }
end
and for show
def show
...
respond_to do |format|
format.html
format.json { render json: { type: 'FeatureCollection', features: poi_geojson + track_geojson} }
end
For index, all work fine and my json is good. I call this method for build json.
Methods for show
def poi_geojson
{
type: 'Feature',
RGeo::GeoJSON.encode(#poi.lonlat),
properties: {
name: #poi.name,
:'marker-color' => '#00607d',
:'marker-symbol' => 'circle',
:'marker-size' => 'medium'
}
}
end
def track_geojson
{
type: 'Feature',
geometry: RGeo::GeoJSON.encode(#track.path),
properties: {
:'color' => '#ff7800',
:'weight' => '5',
:'opacity' => '0.65'
}
}
end
Methods for index
def pois_geojson
#pois.map do |poi|
{
type: 'Feature',
RGeo::GeoJSON.encode(poi.lonlat)
properties: {
name: poi.name,
:'marker-color' => '#00607d',
:'marker-symbol' => 'circle',
:'marker-size' => 'medium'
}
}
end
end
def tracks_geojson
#tracks.map do |track|
{
type: 'Feature',
geometry: RGeo::GeoJSON.encode(track.path),
properties: {
:'color' => '#ff7800',
:'weight' => '5',
:'opacity' => '0.65'
}
}
end
end
As you can see, the methods are similars, but I don't understand why for index it work fine, and not for the show.
I have this error :
`undefined method '+' for #`
for this line :
`format.json { render json: { type: 'FeatureCollection', features: poi_geojson + track_geojson} }`
There is no + method for hash instances, to form an array from two hashes you can do the following:
[pois_geojson, tracks_geojson]
The reason why this works for pois_geojson and tracks_geojson is because both of them are already arrays.

Rails json response including nested reources and their methods

Hello i"m trying desperately to render json that includes methods within my included nested resources. I tried many variants but just can't get that thing to run.
This is what i have:
format.json {render json: #user, :include => [ :votes, :petitions, :roles ] }
And that is what i had hoped to work
format.json {render json: #user, :include => {
:votes => { :methods => [ :status, :count_users_voted ] },
:petitions => { :methods => [:status, :count_users_voted] },
:roles
}
}
Any hints anyone?
Add something like this to your User model:
def as_json(options = { })
super((options || { }).merge({
:methods => [:agrees, :disagrees]
}))
end
def agrees
self.liked_by_count
end
def disagrees
self.disliked_by_count
end
Pretty straight forward, I hope this helps

JSON Rendering: How to include the opening bracket description?

I have some Ruby code that is putting out JSON like this:
def nearby
##bathrooms = Bathroom.geo_scope(:origin =>[params[:lat],[params[:lon]]], :within => 5)
lat = params[:lat]
lon = params[:lon]
##bathrooms = Bathroom.geo_scope(:within => 5, :origin => [45.580639,-122.677682], :order=>'distance')
#bathrooms = Bathroom.geo_scope(:within => 3, :origin => [lat,lon], :order=>'distance')
respond_to do |format|
format.json { render :json => #bathrooms }
format.js { render :nothing => true }
end
end
The result is something like this:
[{"ID":129,"access":"1","avail":"0","bathroomtype":"0","city":"PORTLAND","comment":"","country":"US","created":"0000-00-00 00:00:00","directions":"The two bathrooms are in the long hallway at the back of the restaurant, past the bar.","distance":"2.94986114636676","lat":"45.539217","lon":"-122.661795","modifed":"0000-00-00","name":"Echo","postal":"97212-3727","slug":"echo-portland170","source":"","state":"OR","street":"2225 NE Martin Luther King Jr. Blvd"},
What I don't know how to do is to name the set? For example, after the first enclosing bracket I would like to name the set bathrooms. How can I do this is Rails?
Try:
render json: { bathrooms: #bathrooms }
It looks like #bathrooms is a list, so you can't assign keys to elements in lists. You'll need to make a map first. For example, if you only want the first element:
format.json { render :json => {:bathrooms => #bathrooms[0]} }
To set all list elements:
format.json { render :json => {:bathrooms => #bathrooms} }

index 49793 out of string

I have a strange problem, i can't even get the source of it.
I'm using ajax GET request to a specified url, that routes to :controller => pages, :action => make_affiche_link, there i have the following:
#album = Album.find( params[:album_id] )
#upd = { :affiche_id => params[:affiche_id] }
if #album.update_attributes( #upd )
#out = {:key => '1', :message => "success"}
render :json, #out.to_json
else
#out = {:key => '0', :message => "something bad is going here..."}
render :json => #out.to_json
end
and what i get is this:
index 49793 out of string
And i have both :affiche_id and :album_id in params properly
Thank you for any help!
It is Json #out = {:key => '1', :message => "success"}, you try convert Json to Json #out.to_json. Use render :json, #out

to_json :include :order?

Is it possible to order included models?
format.json { render :json => #client.to_json(:include => { :videos => { :order => 'sortorder' } }) }
You need made when you create your #client. In your SQL request

Resources