Rails返回JSON而不是HTML [英] Rails return JSON instead of HTML

查看:91
本文介绍了Rails返回JSON而不是HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ruby on rails Web应用程序,但是我希望它像Web服务一样工作,而不是HTML来返回JSON。我想要所有CRUD方法。我希望将整个页面呈现为JSON,到目前为止,我只在Show and Edit中为 User 变量实现了此功能。但是我希望整个页面,所有CRUD方法都显示为JSON。

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

到目前为止,我发现这个 render json:@user ,但是我希望整个页面都呈现为JSON,而不仅仅是变量。以及所有URL的所有CRUD方法。

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.

编辑:如果我在 routes.rb 中添加资源:用户,默认值:{format::json} ,然后我收到错误消息缺少模板用户/索引,应用程序/索引,{:locale => [:en] ,:formats => [:json],:variants => [],:handlers => [:erb,:builder,:raw,:ruby,:coffee,:jbuilder]}

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

推荐答案

尝试索引页面

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

之后,您将具有 http:// localhost:3000 / users。 json http:// localhost:3000 / user / 1.json 页面呈现为JSON和HTML,不含 .json

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"

这篇关于Rails返回JSON而不是HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆