Rails return JSON instead of HTML

不羁的心 提交于 2020-04-11 18:36:51

问题


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:


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"



来源:https://stackoverflow.com/questions/33742304/rails-return-json-instead-of-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!