Rendering xml or json data from the controller method is very easy. We have to just follow this syntax.
Example(xml):
def index
@users = User.all
respond_to do |format|
format.xml {render :xml => @users}
end
end
For rails 4 we can also write it like this:
def index
@users = User.all
render :xml => @users
end
render :xml will automatically call to_xml on the object @users.
But we need a .builder template to display this data i.e index.xml.builder.
Example(json):
def find_location
@location = Location.first
render :json => @location
end
We generally render data in json format when there is an ajax call like this:
$.ajax({
type: "GET",
url: "/find_location",
dataType: "json",
success: function(data){
alert(data.name)
}
});
We can use various template engines like jbuilder,rabl for rendering json response data.
0 Comment(s)