Whizzil
Whizzil

Reputation: 1364

Rails return JSON instead of HTML

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]}"

Upvotes: 0

Views: 6922

Answers (1)

IgorLeonenko
IgorLeonenko

Reputation: 29

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"

Upvotes: 2

Related Questions