Returning JSON from Ruby on Rails api - ruby-on-rails

I inherit a RoR api, that provides that to a angular app. I am new to RoR and I am having difficulties with the way the api returns data in json.
def getLocations
location = params[:name]
query = "select * from view_locations where lower(location_name) like lower('#{location}%') limit 4 "
propAll = Property.connection.select_all(query)
respond_to do |format|
if !propAll.blank?
format.json { render json: {status:"ok", data:propAll}}
else
format.json { render json: {status:"error"}}
end
end
end
This code returns this array:
[{"location_name":"Nuevo León","id":"19","quantity":"5988","type":"State"},{"location_name":"Naucalpan de Juárez, México","id":"09","quantity":"131","type":"City"},{"location_name":"Nayarit","id":"18","quantity":"91","type":"State"},{"location_name":"Nacajuca, Tabasco","id":"013","quantity":"20","type":"City"}]
Is there any way that I could return the JSON instead of an array?
If its not possible, how should I use the returned array in Angularjs, right now we are going through every array element and pushing it in another array .
Thanks, for any help provided
Alberto

Related

How to print in rails after a create api is called from an android

I have an android app and a rails app. When a order is made from android, it calls create order API in rails app. So whenever a create order is successful in rails app,i want to perform a print action that prints the order bill using the data send from the android.
But the controller i created only gives a response either in json or html format. i.e
class API::V1::OrdersController << Api::ApiController
def create
#order = Order.create(
item: params[:item],
quantity: params[:quantity],
price: params[:price]
)
if #order.persisted?
respond_to do |format|
format.json { notice: 'Order successfully created.' }
format.html { render :print }
end
end
end
end
This will only give back the response of 'Order successfully created.' when json is used or the html format page written in 'print.html.slim' to the android.
But i want to print a order bill page from 'print.html.slim' when a order is persisted.
print.html.slim
table.table
thead
th Item Name
th Quantity
th Price
tbody
tr
td = #order.item
td = #order.quantity
td = #order.price
Is there any way i can do this ?
What you have and what you seek are two different things.
Since you have set up your Rails server as an API end point, you can only return JSON values. For what you need, you should accept the JSON data in your android app and do what you wish with the data in your app (like displaying the confirmed order)

Rails Controller Display a of List of Resources/Objects?

For my app I have three models: Quotes, Images, Videos, all of them I consider content. I want to call the index action of my ContententController to display a mix of these objects in JSON format. For example, I get something like this back.
[
{ ...image json... },
{ ...image json... },
{ ...video json... },
{ ...quote json... },
{ ...image json... }
]
How would I approach this? I feel like this has something to do with an SQL UNION? Thank you!
If you consider all three "content", then you really should use a single table inheritance strategy where they all inherit from the Content model. That way you can call
#Contents = Content.all.whatever
Instead of having to call each and then mix them together, or getting more complex then you need with the query. Turning them into JSON would then be easy considering each object would have its normal to_json method called on it, when doing something like this
format.json {render :json => #Contents}
def index
#quotes = Quotes.all
#images = Image.all
#videos = Video.all
#contents = #quotes + #images + #videos
format.json {render :json => #contents}
end
I think you can just append each object, but I wont recommend you to do that.

Association data into json output in Rails

I have a model where I can get my index action to return a list of objects back as json but I need each one to return a list of sub elements over an association.
I have tried the following but the coasters are not being output. Is there a way this can return each parks coasters?
format.json do
render json: Park.scoped(include: :coasters)
end
Try something like :
render json: Park.joins(:coasters).select("parks.*,coasters.*") # parks.*, coasters.* refers to actual table names
This could be achieved with active_model_serializers gem.
the code should looks like this
format.json do
render json: Park.scoped.to_json(include: :coasters)
end
more info can be find here https://github.com/rails/rails/pull/2200

Rendering large database record set as JSON in rails

Is there a way to present a large record set in JSON format without consuming large amount of memory? For example I have the following query:
...
records = Records.where(query)
respond_to do |format|
format.html
format.json { render :json => records.to_json }
end
There are times that records will contain thousands of entries and JSON is strictly used for getting the data without using pagination and such data must fit inside the memory for it to be returned. A Record entry will also contain a lot of fields (I am using MongoDB/Mongoid) and it is necessary to include such fields.
It's almost always a bad idea to return every resource in a database.
You can respond with limited set of results and provide total number of records.
For example:
{
total: 503
records: [
{ id: 1 },
{ id: 2 }
]
}
And add possibility to use limit and offset parameters to iterate through all pages.
There is chapter named Pagination and partial response in free e-book Web API Design describes it.
I would recommend you to read that book. It contains only 30 pages.
upd:
In your case you are able to paginate results using limit and skip mongoid's methods.
records = Records.where(query).limit(params[:limit]).skip(params[:offset])
respond_to do |format|
format.html
format.json { render :json => { total: records.count, records: records }.to_json }
end

Sending a query string to rails respond_to

I am rather new to ruby and rails development.
for the past little while, I have been trying to figure out how I can pass params/query string to a rails respond_to block. I am focusing on the json response.
Say I have the following
def index
#employees = Employee.all
respond_to do |format|
format.html
format.json { render json: #employees }
end
end
and I am looking to only get a json response containing employees who have an id that is greater than 500. What would be the best way to go about this.
I have been trying to make the json request using jQuery.ajax() and I know you can pass data to the server that is formatted to a query, but not sure how to make it work.
The above example is only hypothetical. I am only looking for a way to be able to use a query sting when wanting a json response.
Thanks for the help!
Whatever parameters are sent with the request (in the query string) should be available in your controller (check the params variable). Here's one way to get the Employees with id's at & above 500:
Replace
#employees = Employee.all
with
#employees = Employee.find(:all, conditions: ["id >= ?", 500])
Please note that you don't need to pass anything besides the format to that respond_to block.

Resources