Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Rendering XML and JSON in rails

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 3.06k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: