How to send JSON data using rails - ruby-on-rails

Hi I am trying to create a custom controller that return a method as json.
Here my controller
respond_to :json
def rates
#event = Event.find(params[:id])
respond_with #event.avg_rating
end
Now I have my model with the following method
# returns the average rating for that event
def avg_rating
#avg = self.ratings.average(:stars)
#avg ? #avg : 0
end
However when i get the respond I get this:
3.75
What I would like is a standard json respond either {"event": "3.75"}
But I am not sure what to use to simply transform it to make an answer like that

You will need an actual object to be rendered to json. A hash is usually easiest. And you will want to use render instead of respond_with
render json: {:event => #event.avg_rating}

Related

Rails 6 jbuilder not rendering array properly

I have a problem with rendering array properly with JBuilder on Rails 6 (API only mode).
I basically have a list of registration plates, which I want to fetch via API request
My index view looks like this:
# frozen_string_literal: true
json.array! #registration_plates,
partial: 'registration_plates/registration_plate',
as: :registration_plate
My show view looks like:
# frozen_string_literal: true
json.partial! 'registration_plates/registration_plate',
registration_plate: #registration_plate
And finally partial _registration_plate.json.jbuilder is very simple:
# frozen_string_literal: true
json.id registration_plate.id
json.plate registration_plate.plate.to_s
I do get a normal response from server:
But instead of an array, I get the series of JSON objects
Did anyone have similar problem, or do you have any idea how to solve it?
Than you in advance.
EDIT
Also my controller is configured to render the jbuilder rather than json
# GET /registration_plates
def index
#registration_plates = RegistrationPlate.all
render #registration_plates
end
# GET /registration_plates/1
def show
render #registration_plate
end
And if I change the index action to look like
def index
#registration_plates = RegistrationPlate.all
render json: #registration_plates.to_json(only: %i[id plate])
end
i do get correct output, but then, I defy the sole purpose of jbuilder
update your index to remove render #registration_plates
# GET /registration_plates
def index
#registration_plates = RegistrationPlate.all
end
render #registration_plates renders _registration_plate.json.jbuilder directly without going into index.json.jbuilder

ActiveRecord serialize two different models in at once

I have a controller action (favorites) in my Rails app that returns a JSON object with two keys (companies and jobs). Each key represents a collection of Company or JobDescription objects. What I want to know is if there is a clean way I can serialize both #companies and #jobs. Here is my code:
def favorites
#companies = current_user.companies
#jobs = current_user.job_descriptions
respond_to do |format|
format.html
format.json { render json: {companies: #companies, jobs: #jobs}, root: false }
end
end
I could always refactor my code into two separate JSON calls (one for jobs, one for companies), but I'd prefer to stick with a single call to favorites.
You can use Rails Presenters here!
So, you can have two presenters: CompaniesPresenter and JobsPresenter which will be responsible for building the #companies and jobs objects respectively.
So, in your controller, you would have something like:
#companies = CompaniesPresenter.new(current_user).companies
#jobs = JobsPresenter.new(current_user).job_descriptions
For example, your CompaniesPresenter would look like this:
class CompaniesPresenter
attr_reader :current_user
def initialize(current_user)
#current_user = current_user
end
def companies
# build the companies JSON here
end
end
Here is a tutorial with Rails Presenter Pattern that might be useful.
And, here is an useful video. Hope this helps.
This example works, are you just trying to change the json format? If so...
In the company or job model, you can add an as_json method and format the output as you want.
def as_json(options = {})
{ :name => name }
end

Rails 4 json return on API

I'm creating an API on my application. I currently overrided the as_json method in my model in order to be able to get attached files as well as logo from Paperclip :
def as_json( options = {} )
super.merge(logo_small: self.logo.url(:small), logo_large: self.logo.url(:large), taxe: self.taxe, attachments: self.attachments)
end
Then within my controller, I'm doing :
def index
#products = current_user.products
respond_with #products
end
def show
respond_with #product
end
The problem is that on the index, I don't want get all the attachments. I only need it on the show method. So I tried it :
def index
#products = current_user.products
respond_with #products, except: [:attachments]
end
But unfortunately it's only working on default product attributes (everyting that I merged seems not to be consider). How can I do to not send :attachments?
Thanks
I'd recommend you have a look at active_model_serializers. It will provide a nice and OOP way of handling the kind of object decoration you need - selectively excluding attributes - and much more. There's even a Railscast!

respond_with ArgumentError (Nil location provided. Can't build URI.):

I have a controller that responds_with JSON for all of the RESTful actions, index, create, update etc,
class QuestionsController
respond_to :json
def index
respond_with Question.all
end
end
However, I also have other actions in the controller. For example, in one method, it checks whether a response was correct and then tries to return a variable with a boolean true or false
respond_with correct_response #either true or false
However, this is giving me the error
ArgumentError (Nil location provided. Can't build URI.):
There will also be other methods that I'll wish to respond with multiple values. In Sinatra, you can do this to respond with json
{:word => session[:word], :correct_guess => correct_guess, :incorrect_guesses => session[:incorrect_guesses], :win => win}.to_json
How would I do that in Rails?
So, two questions, what's the proper way to write this
respond_with correct_response
and how to respond_with multiple values in a way similar to the example I showed from a Sinatra app.
Thanks for your help.
You want ActionController::Base#render, not respond_with. The proper way to do what you're trying to achieve here is:
render json: {word: session[:word], correct_guess: correct_guess, incorrect_guesses: session[:incorrect_guesses], win: win}
respond_with is actually OK for this scenario--it just happens to do some magic for you and relies on having access to info it needs; take a look at Rails 4.1.9's actionpack/lib/action_controller/metal/responder.rb.
In your case, ArgumentError (Nil location provided. Can't build URI.) is actually telling the truth--it's trying to determine a URL to use from the location header setting but isn't able to figure it out. I'd wager you could get your code working if you gave it one:
class QuestionsController
respond_to :json
def index
respond_with Question.all, location: questions_url
end
end

Accessing virtual attribute from JSON

My setup: Rails 2.3.10, Ruby 1.8.7
I have experimented, without success, with trying to access a virtual attribute in a model from a JSON call. Let's say I have the following models and controller code
class Product
name,
description,
price,
attr_accessor :discounted_price
end
class Price
discount
end
class ProductsController
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #product }
end
end
end
What I like is to have the JSON output also include Product.discounted_price which is calculated in real-time for each call, ie discounted_price = Price.discount * Product.price. Is there a way to accomplish this?
SOLUTION:
With the initial help from dmarkow, I figured it out, my actual scenario is more complex than the above example. I can do something like this, in the Product model, add a getter method
def discounted_price
...# do the calculation here
end
In the JSON call do this
store = Store.find(1)
store.as_json(:include => :products, :methods => :discounted_price)
You can run to_json with a :methods parameter to include the result of those method(s).
render :json => #product.to_json(:methods => :discounted_price)
Have a look at the gem RABL, as shown in this railscast:
http://railscasts.com/episodes/322-rabl?view=asciicast
RABL gives you fine grained control of the json you produce, including collections and children.

Resources