Render JSON in Rails - ruby-on-rails

I want to see the following code in json format. When I do so I get a blank page with no content. In the rubymine debugger I have the correct information in json format.
include Java
require 'net/http'
class PatientRecordController < ApplicationController
def index
url = 'http://localhost:8080/patient/record/v2/'
data_raw = Net::HTTP.get_response(URI.parse(url)).body
#data_json = ActiveSupport::JSON.decode(data_raw)
respond_to do |format|
format.json {render json: #data_json}
end
end
end

You must add .json at the end of the path you enter into the browser.

What is the path to this particular index action? This code should indeed render JSON, which your debugger is indicating that it indeed is.
The URL you should be visiting is something akin to http://your_host/patient_records/index.json.

If you don't want to change the request to include .json, you can just drop the respond_to block render json: #data_json on its own will work.

Related

can I use rabl without using .json in the url?

I have rabl up and running.
I have this in routes:
get 'biblios/collection/:biblio_urn' => 'biblios#biblio_rabl', as: 'collection_biblio'
in the controller:
def biblio_rabl
biblio = Biblio.where(biblio_urn: params[:biblio_urn]).take
end
This url points to the correct result :
http://localhost:3000/dts/biblios/collection/urn:cts:froLit:ed_desmarez:1900
I would like that url to always respond using rabl and showing the the template dts/biblios/biblio_rabl.json.rabl
I mean without adding .json at the end of the url.
I have tried this in the routes.rb, but it doesn't redirect :
get 'biblios/collection/:biblio_urn' => 'biblios#biblio_rabl', as: 'collection_biblio', to: redirect('biblios/collection/%{biblio_urn}.json')
Is that possible at all?
You can force the response to be json by changing the request format in the controller:
request.format = :json
Then make sure you have a respond_to block like this because it's always better to be explicit about your responses:
def biblio_rabl
respond_to do |format|
format.json { json: Biblio.where(biblio_urn: params[:biblio_urn]).take }
end
end

Rails: Is it neccessary to wrap my POST response in a respond_to block?

I have an AJAX form that sends a POST request to the controller. The controller responds in JSON.
Here, reponse is JSON:
def send_form_response(response)
render json: response
end
The above works fine but I keep seeing examples that use respond_to. My form still works when I wrap my response in the respond_to block.
def send_form_response(response)
respond_to do |format|
format.json { render json: response }
end
end
Does using respond_to give me any benefits? Will anything bad happen if I don't? Or does it make no difference in this case?
respond_to is used to handle multiple responses in the controller#action
If the client wants HTML in response to this action, just respond as
we would have before, but if the client wants XML, return them the
list of people in XML format." (Rails determines the desired response
format from the HTTP Accept header submitted by the client.)
Say for example, If you want send_form_response(response) to respond with HTML and JSON, then you would do it like this
def send_form_response(response)
respond_to do |format|
format.html
format.json { render json: response }
end
end
You can do the same with respond_with
respond_to :html, :xml, :json
def send_form_response(response)
respond_with response
end
So, to answer your questions
Does using respond_to give me any benefits?
Not in your case, where you are requesting only one response
Will anything bad happen if I don't?
Not in your case, no.
Does it make no difference in this case?
No, not at all.

Restful api with rails

I am learning how to write a restful API using RoR and have a question related to it. So, I will explain what I did along with the code.
This is how my controller looks like:
class EmployeesController < ApplicationController
require 'rest_client'
def index
uri = "localhost:3000/employees"
rest_resource = RestClient::Resource.new(uri)
users = rest_resource.get # will get back you all the detail in json format, but it will we wraped as string, so we will parse it in the next step.
#users = JSON.parse(users, :symbolize_names => true) # convert the return data into array
#users.each do |u|
logger.info(u.id)
end
# return based on the format type
respond_to do |format|
format.json {render json: #users}
format.xml {render xml: #users}
format.html
end
end
end
In my Gemfile, I have included rest-client as well.
gem 'rest-client'
My routes are :
root 'employees#index'
resources 'employees'
Hope everything is fine till now.
Now, when I send:
-> Curl request to 'http://localhost:3000/employees', it gets stuck.
-> Get request(by typing in the browser) to 'http://localhost:3000/', it get stuck here as well.
What is that which I am missing?
You don't need RestClient as you're writing a server here, not a client. The browser acts as the client. Remove the call to localhost as it's creating a loop.
The URL for this should already be set in your routes.rb, maybe using:
resources :users
Assuming this is a typical app, the show function should be reading from the database using ActiveRecord.
class EmployeesController < ApplicationController
def index
#users = User.all
respond_to do |format|
format.json {render json: #users}
format.xml {render xml: #users}
format.html
end
end
end
Do you have some other application running on localhost:3000? Because if not, then what your server does is calling himself again and again, causing a loop.
If you do have some other application, which fetches users from database, then be sure its running on some other port, other than this your rails app.
If you have only 1 app, then you don't need rest client.
You actually can do this without any additional gem. You just need to declare your routes according to what you want to expose to your API users and return the type (xml, json, ...) accordingly.

Double Render Error rails controller

So i'm tyring ot create a custom method in my controller
So far it looks like this
def url
require 'json'
url = url appears here
doc = Nokogiri::HTML(open(url))
doc.css(".ticket-price .h4").each do |t|
json = t.text
respond_to do |format|
format.json { render :json => {:seatname => json}}
end
end
end
However when i run this i get this error
AbstractController::DoubleRenderError
I can't see where the its being called twice? my guess however is that because its inside the each statement. What would be the best way to display the two seat names that come back in json so that it looks like this:
"seatname": "seat1",
"seatname": "seat2"
Thanks
Sam
This should work:
def url
require 'json'
url = url appears here
doc = Nokogiri::HTML(open(url))
// Constructing an array of hash
response_hash = doc.css(".ticket-price .h4").map{ |t| {seatname: t.text} }
respond_to do |format|
format.json { render :json => response_hash }
end
end
Like Max mentioned, in your code respond_to gets called for every matching element. Instead you can construct an array of hash, and then render that.
Give this a shot:
def url
require 'json'
url = url appears here
doc = Nokogiri::HTML(open(url))
response_hash = doc.css(".ticket-price .h4").map { |t| ["seatname", t.text] }.to_h
respond_to do |format|
format.json { render :json => response_hash }
end
end
In your current code, the respond_to block is being called once for each matching element in the return value of doc.css(...), which is causing the DoubleRenderError. To fix that, you need to separate constructing your response data from actually sending it. Does that help?

Rails Controller - What is the purpose of "respond to do format" html and json?

Ruby on Rails Question:
Inside the controller you have seven REST actions. Almost all of them have respond to do format xml/html or json. I have no idea what this means. Can you please explain it's purpose.
For example:
def index
#tweets = Tweet.all
respond_to do |format|
format.html
format.json { render json: #tweets }
end
end
What is the purpose of the "respond to" part that contains the html and json? What do these formats do?
Also, what is the difference between xml and html? Sometimes I see xml and other times html.
Thank you
Its just a way of telling your controller how to respond to different request types. For example your client could want html or xml information from you:
def index
#people = Person.find(:all)
respond_to do |format|
format.html
format.xml { render :xml => #people.to_xml }
end
end
What that says is, "if the client wants HTML in response to this action, just respond as we would have before, but if the client wants XML, return them the list of people in XML format." (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

Resources