In Rails, How to Render Json Using a View

In Rails, how do you render JSON using a view?

You should be able to do something like this in your respond_to block:

respond_to do |format|
format.json
render :partial => "users/show.json"
end

which will render the template in app/views/users/_show.json.erb.

rails - how to render a JSON object in a view

I would recommend that you write that code in an helper itself. Then just use the .to_json
method on the array.

# application_helper.rb
def comments_as_json(comments)
comments.collect do |comment|
{
:id => comment.id,
:level => comment.level,
:content => html_format(comment.content),
:parent_id => comment.parent_id,
:user_id => comment.user_id,
:created_at => comment.created_at
}
end.to_json
end

# your_view.html.erb
<%= comments_as_json(@conversation_comments) %>

Rendering json in ruby on rails views

Try this

render json: @payment.to_json

Ruby on Rails: Rendering json and layout together in an action

I want to render this file along with the sending a json response (I need the json data to do some actions.)

TL;DR: This is not possible due to http proto specs. One should do two separate requests.

The easiest way to accomplish your task is to render html (via erb or whatever,) then call another controller action (say, asset_map_fullscreen_json) using javascript/AJAX from the page rendered. On the other hand, you might use the same endpoint (while still separating main request and subsequent AJAX call):

respond_to do |format|
format.html { render layout: false } # or whatever to simply render html
format.json { render json: @next_level.to_json }
end

Render json response from controller to view

There are lots of better options using js libraries, but if you want to just use jquery, you should create the table using plain HTML (giving an id to the tbody). Then use js to create a string and concatenate it with every attribute you need, for instance:

var tr = '<tr><td>';
tr += jsonResponse.firstAttribute;
tr += '</td><td>';
tr += jsonResponse.secondAttribute;
tr += '</td>';
...
$('#you-table-body-id').append(tr);

by doing so you will concatenate this chunk of html containing the data you want to exhibit in your site.

Rails render json displaying on screen



Since you are triggering a manual ajax form submission, remote: true is not required in the form. Just remove remote: true from the form and prevent the form submission event once it is triggered. Then, the code will look like

 $("#payment-form").submit(function(event){
var jqxhr = $.ajax({
url: '/give',
type: 'POST',
dataType: 'json',
data: $form.serialize()
})
.done(function() {
console.log(jqxhr['responseText']);
$('#new-gift').hide(function() {
$('#confirm-gift').show();
});
});
.fail(function() {
})
.always(function() {
});
event.preventDefault();
});



Hope this will help.

Rails 4 - rendering JSON from a view

Part of my solution was based on this answer to another question: adding defaults: {format: :json} to my routes file lets me go to /api_docs and see the JSON when the action is just def index ; end with no render. The RSpec test still fails though. The full line from my routes file: resources :api_docs, only: [:index], defaults: {format: :json}.

Thanks to this guy with the same problem and his gist, I added render_views to my describe block and got my test to pass:

describe ApiDocsController do
render_views

...

let(:get_index) { ->{ get :index } }

describe 'JSON response' do
subject {
get_index.call
JSON.parse(response.body)
}

it 'includes the API version' do
subject['apiVersion'].should_not be_nil
end
end

Rails 4 render json with multiple objects and includes

Without adding any gems:

def index
boats = Boat.includes(:year)

render json: {
boats: boats.as_json(include: { year: { only: :name } }),
numTotalBoats: boats.count
}
end

At some point though, I believe you should use stand-alone serializers:

Note: Depending on whether you're using pagination gem or not, you might need to change .count calls below to .total_count (for Kaminari) or something else that will read the count correctly from paginated collection.

I recommend using ActiveModel Serializers and this is how it would be accomplished for your case.

Start by adding the gem to Gemfile:

gem 'active_model_serializers', '~-> 0.10'

Overwrite the adapter in config/initializers/active_model_serializer.rb:

ActiveModelSerializers.config.adapter = :json

Define serializers for your models,

# app/serializers/boat_serializer.rb
class BoatSerializer < ActiveModel::Serializer
attributes :name

has_one :year
end

# app/serializers/year_serializer.rb
class YearSerializer < ActiveModel::Serializer
attributes :name
end

And finally, in your controller:

boats = Boat.includes(:year)

render json: boats, meta: boats.count, meta_key: "numTotalBoats"

And you will achieve:

{
"boats": [
{
"name": "Boaty McBoatFace",
"year": {
"name": "2018"
}
},
{
"name": "Titanic",
"year": {
"name": "1911"
}
}
],
"numTotalBoats": 2
}

Adding that count in each index controller is a bit tedious, so I usually end up defining my own adapters or collection serializers in order to take care of that automatically (Tested with Rails 5, not 4).

# lib/active_model_serializers/adapter/json_extended.rb
module ActiveModelSerializers
module Adapter
class JsonExtended < Json
def meta
if serializer.object.is_a?(ActiveRecord::Relation)
{ total_count: serializer.object.count }
end.to_h.merge(instance_options.fetch(:meta, {})).presence
end
end
end
end

# config/initializers/active_model_serializer.rb
ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonExtended

# make sure to add lib to eager load paths
# config/application.rb
config.eager_load_paths << Rails.root.join("lib")

And now your index action can look like this

def index
boats = Boat.includes(:year)

render json: boats
end

And output:

{
"boats": [
{
"name": "Boaty McBoatFace",
"year": {
"name": "2018"
}
},
{
"name": "Titanic",
"year": {
"name": "1911"
}
}
],
"meta": {
"total_count": 2
}
}

I think it's a little easier to parse this count for different endpoints and you will get it automatically while responding with a collection, so your controllers will be a little simpler.

Ruby API response view : how can I render a JSON response?

There are multiple ways of achieving what you want. You could merge! the response into the jbuilder root.

json.merge! @response

The above merges all key/value-pairs into the jbuilder root. You could also opt to extract! specific attributes.

json.extract! @response, :error

Alternatively you can simply render it in the controller, since you've already composed the structure the following would be enough.

render json: @response


Related Topics



Leave a reply



Submit