0

I have a ruby on rails web app, but I want it to act like a web service and instead of HTML to return JSONs. I want this for all CRUD methods. I want the whole page to be rendered as JSON, so far I only achieved this in Show and Edit for the User variable. But I want the whole page, for all CRUD method to show as JSONs.

    def index
    @users = User.all
end


def show
    @user = User.find(params[:id])

    # Render json or not
    render json: @user
end


def new
    @user = User.new
end


 def edit
    @user = User.find(params[:id])
end


def create
    @user = User.new(user_params)

    if @user.save
        redirect_to @user
    else
        render 'new'
    end
end


def update
    @user = User.find(params[:id])

    if @user.update(user_params)
        redirect_to @user
    else
        render 'edit'
    end
end


def destroy
    @user = User.find(params[:id])
    @user.destroy

    redirect_to users_path
end

So far I found this render json: @user, but I want the whole page to be rendered as JSON and not just the variable. And every URL, for all CRUD methods.

EDIT: if I add to my routes.rb something like this resources :users, defaults: {format: :json} then I get error message "Missing template users/index, application/index with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}"

1 Answer 1

2

Try for index page

respond_to do |format|
  format.html { @users }
  format.json { render json: json_format(@users) }
end

And for all other, where User it's one object

respond_to do |format|
  format.html { @user }
  format.json { render json: json_format(@user) }
end

after this you will have http://localhost:3000/users.json and http://localhost:3000/user/1.json pages wich rendered as JSON and HTML without ".json"

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

2 Comments

Is it possible to have JSON rendering without specifically calling .json in a URL? e.g. localhost:3000/users and so it automatically shows JSON?
So if you need only JSON, you must did like you realise. In routes you write resources :users, defaults: {format: 'json'}. And in controller render json:@user or @users. If it not help, just show what you local server return in console

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.