-2

So, I want to make my models render to json object so it can be used for a Android Device. I have all the models setup, but because I used the sccafold generate model call, I don't have any methods in the controller of the models... How do I generate the actual code, so that I can render the model in json?

I am using

$ rails --version
Rails 3.2.13
Sriram Venkatesh
  • 593
  • 2
  • 8
  • 22

1 Answers1

1

From the Ruby on Rails guide:

render :json => @product

So, inside the generated controller you can do something like this:

def show
    @user = User.find( params[:id] )
    respond_to do |format|
        format.json{
            render :json => @user.to_json
        }
    end
end

Tip: 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.

You can find some examples on questions that have been answered previously:

Community
  • 1
  • 1
Diego Cardozo
  • 261
  • 1
  • 6
  • yeah but where do I put it if the code generated from scafollding is: class PostsController < InheritedResources::Base before_filter :authenticate_user! end – Sriram Venkatesh Apr 25 '13 at 01:58
  • I edited the answer and added some code to give you a better idea of where this code is supposed to go. – Diego Cardozo Apr 25 '13 at 05:08