My Rails controller action looks something as trivial as the following:
def show
#batter_rankings = DfsHittersBeta.all
#pitcher_rankings = DfsSpBeta.all
render :json => ??
end
In this case, both collections above each have their own serializer. I do want to have them as part of one API. So the API will ultimately look like:
{'pitchers' => [#pitcher_rankings],
'hitters' => [#hitter_rankings]
}
I'm not entirely sure how to pass both models to render as json each with their own serializer though and then perhaps a global serializer which allows me to specify how the final output looks.
You can include both pitchers and hitters in your JSON response like this:
render json: {pitchers: #pitcher_rankings, hitters: #hitter_rankings}
Related
I'm updating my Rails app to active_model_serializers 0.10.4 but I'm having trouble updating a necessary feature: the ability to add request information to every json response from the controller.
In AMS 0.9.x I used to do it by using default_serializer_options but that funcionality is gone, and apparently the only way to achieve this is manually adding the meta key to EVERY request.
Has anyone found a workaround to make this work?
in config/initializers/active_model_serializer.rb file add this line:
ActiveModel::Serializer.config.adapter = :json
The example below will add a data attribute at the top level, and render the #users objects under data key in your response.
In your controller:
def index
#users = User.all
render json: #users, root: "data"
end
If you're going for a JSON API schema with a meta tag and a data tag with objects for every response, simply change initializer to
ActiveModel::Serializer.config.adapter = :json_api
and controller to
def index
#users = User.all
#extra_meta = {"totalCount": #users.size}
render json: #users, root: "data", meta: default_meta_attributes(#users, #extra_meta)
end
In my case default_meta_attributes is in the base controller and merges in some details about the request like current_user_id, etc with the option to add additional details in each method
Could you give a more specific example of what you're trying to do? You could make an ApplicationSerializer and set the serialization_scope to :view_context then do whatever you want in the serializer. You could also customize the JSON adapter. Or, if you want, you can prepend a module to SerializableResource to add options.
By default calling rails.model.to_json
Will display something like this:
{"name":["can't be blank"],"email":["can't be blank"],"phone":["can't be blank"]}
Instead of message i need to generate some status code that could be used on service client:
[{"field": "name", "code": "blank"}, {"field": "email", "code": "blank"}]
This approach is very similar to github api v3 errors - http://developer.github.com/v3/
How can I achieve this with Rails?
On your model you can modify the way as json operates. For instance let us assume you have a ActiveRecord model Contact. You can override as_json to modify the rendering behavior.
def Contact < ActiveRecord::Base
def as_json
hash = super
hash.collect {|key, value|
{"field" => key, "code" => determine_code_from(value)}
}
end
end
Of course, you could also generate the json in a separate method on Contact or even in the controller. You would just have to alter your render method slightly.
render #contact.as_my_custom_json
In your controller, when you render the output, in your case JSON content, add the following :
render :json => #yourobject, :status => 422 # or whatever status you want.
Hope this helps
So I have a model called Image that belongs_to :user. Each user has a first and last name.
I have a flash app that I am returning a json object back to of Images.
the service I will be calling on the Images controller would look something like this
def getimages
#images = Image.all
render :json => #images
end
My json would look something like this
[{"image":{"created_at":"2011-01-22T19:04:30Z","img_path":"assets/img/bowl_93847566_3_0.png","updated_at":"2011-01-22T19:04:30Z","id":9,"user_id":3}}]
what I would like to do is also include the users first and last name with in the image object that gets passed back.
once I have an image object I am able to do something like image.user.first_name but I am not clear how I would return something like an array of image objects and include the user along with it.
what would be great is if I could get my array of images to look like the following.
[{"image":{"created_at":"2011-01-22T19:04:30Z","img_path":"assets/img/bowl_93847566_3_0.png","updated_at":"2011-01-22T19:04:30Z","id":9,"user_id":3, "first_name":"Matthew", "last_name":"Wallace"}}]
I am thinking this may include adding some kind of model method or somthing that I am not familiar with.
What would be the best practice for achieving this?
You could:
render :json => #images.to_json(:include => :users)
See http://apidock.com/rails/ActiveRecord/Serialization/to_json (and http://apidock.com/rails/Array/to_json shows it works on Arrays). Finally, http://apidock.com/rails/ActionController/Base/render describes using to_json in a json render as optional and not required, which implies it should cause no harm (I couldn't see another way to pass the required options in).
Perhaps cleaner json:
render :json => #images.to_json(:include => { :user => { :only => [:first_name, :last_name] } })
Besides the answer provided by #apneadiving, you can also override the Image's to_json method and return a string containing whatever JSON you need.
I've got some data in Rails that I want to render as JSON data. What I'm doing right now is simply finding all instances of a Model and calling render :json=>data.
data = Data.find(:all)
render :json => data
However, Rails is including the model name in each JSON object. So my JSON data ends up looking like this:
[{modelname:{propertyName: 'value',...}},{modelname:{propertyName: 'value2',...}}]
instead of this:
[{propertyName:'value',...},{propertyName:'value2',...}]
The modelname is always the same and I don't want it to be there.
I changed the option to render the root in the JSON data in one of the Rails initializers but that affects everything that I want rendered as JSON, which I don't want to do for this project.
In this case, I want to be able to do this on a case-by-case basis.
How can I do this? Thanks in advance.
With Rails 3, you can use active_model_serializers gem1
that allows you to specify rootless rendering of an object like this:
render :json => data, :root => false
I did not find a way to do this by passing options to the to_json method (and I don't believe there is such an option). You have more alternative to do this, any class that inherits from ActiveRecord::Base will have include_root_in_json.
Do something like this.
Data.include_root_in_json = false
data = Data.find(:all)
render :json => data
Hope this gets you going.
Ok let's try this then.
DataController < ApplicationControlle
private
def custom_json(data)
Data.include_root_in_json = false
data.to_json
Data.include_root_in_json = true
data
end
end
Then your redirect would look like this
data = Data.find(:all)
render :json => custom_json(data)
It's pretty silly code I wish I could think of something else entirely. Let me ask you this: What is it about having the model name included in the json data ?
With Rails 3, I found this way better to do. Override the as_json in your model and do as follows:
def as_json(options = {})
super(options.merge :methods => [:some_method_that_you_want_to_include_result], :include => {:child_relation => {:include => :grand_child_relation } })
end
Is there an easy way to return data to web service clients in JSON using Rails?
Rails resource gives a RESTful interface for your model. Let's see.
Model
class Contact < ActiveRecord::Base
...
end
Routes
map.resources :contacts
Controller
class ContactsController < ApplicationController
...
def show
#contact = Contact.find(params[:id]
respond_to do |format|
format.html
format.xml {render :xml => #contact}
format.js {render :json => #contact.json}
end
end
...
end
So this gives you an API interfaces without the need to define special methods to get the type of respond required
Eg.
/contacts/1 # Responds with regular html page
/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes
/contacts/1.js # Responds with json output of Contact.find(1) and its attributes
http://wiki.rubyonrails.org/rails/pages/HowtoGenerateJSON
Rails monkeypatches most things you'd care about to have a #to_json method.
Off the top of my head, you can do it for hashes, arrays, and ActiveRecord objects, which should cover about 95% of the use cases you might want. If you have your own custom objects, it's trivial to write your own to_json method for them, which can just jam data into a hash and then return the jsonized hash.
There is a plugin that does just this,
http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/
And from what I understand this functionality is already in Rails. But go see that blog post, there are code examples and explanations.
ActiveRecord also provides methods to interact with JSON. To create JSON out of an AR object, just call object.to_json. TO create an AR object out of JSON you should be able to create a new AR object and then call object.from_json.. as far as I understood, but this did not work for me.