-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
1
  • The answer can easily be found with a quick google search. Commented Apr 25, 2013 at 1:33

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

yeah but where do I put it if the code generated from scafollding is: class PostsController < InheritedResources::Base before_filter :authenticate_user! end
I edited the answer and added some code to give you a better idea of where this code is supposed to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.