Background and my research
I would like to send data from server to client without reloading the page on the browser. I was reading Rails guide and using JSON seemed promising. (Correct me if I am wrong).
2.2.8 Rendering JSON
JSON is a JavaScript data format used by many AJAX libraries. Rails
has built-in support for converting objects to JSON and rendering that
JSON back to the browser:render :json => @product You don’t need to call to_json on the object
that you want to render. If you use the :json option, render will
automatically call to_json for you.
Problem
I want to be able to render this JSON object back in the browser side. The following are appropriate code for the problem.
VideosController
class VideosController < ApplicationController
include VideosHelper
def home
@video = Video.last
end
def next
@next_video = next_video(params[:id])
render :json => @next_video
end
end
next.json.erb
{
"title": "<%= @video.title %>"
"url": "<%= @video.url %>"
"youtube_id": "<%= @video.youtube_id %>"
"genre": "<%= @video.genre %>"
"category": "<%= @video.category %>"
"likes": "<%= @video.likes %>"
"dislikes": "<%= @video.dislikes %>"
"views": "<%= @video.views %>"
"user_id": "<%= @video.user_id %>"
"created_at": "<%= @video.created_at %>"
"updated_at": "<%= @video.updated_at %>"
}
If I want to render @next_video JSON object on home action. How do I do this?
You need some js handler i guess. Something like that in home.html.erb:
also in next.json.erb you should change @video to @next_video(since you don’t have @video initialized in next action). Also one more suggestion – you can use REST those renaming next to show and deleting home(since you can replace it with show now) and you will need to change previous code to:
Where @video.next will return id of the next video.