简体   繁体   English

Rails返回JSON而不是HTML

[英]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. 我在Rails Web应用程序上有一个ruby,但是我希望它像Web服务一样工作,而不是HTML来返回JSON。 I want this for all CRUD methods. 我想要所有CRUD方法。 I want the whole page to be rendered as JSON, so far I only achieved this in Show and Edit for the User variable. 我希望将整个页面呈现为JSON,到目前为止,我仅在Show和Edit中为User变量实现了此目的。 But I want the whole page, for all CRUD method to show as JSONs. 但是我希望整个页面,所有CRUD方法都显示为JSON。

    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. 到目前为止,我发现了这个render json: @user ,但是我希望整个页面都以JSON形式呈现,而不仅仅是变量。 And every URL, for all CRUD methods. 以及所有URL,适用于所有CRUD方法。

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]}" 编辑:如果我添加到我的routes.rb这样的resources :users, defaults: {format: :json}然后我收到错误消息“缺少模板用户/索引,应用程序/索引与{:locale => [:en] ,:formats => [:json],:variants => [],:handlers => [:erb,:builder,:raw,:ruby,:coffee,:jbuilder]}“

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 对于所有其他用户,User是一个对象

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" 之后,您将拥有http:// localhost:3000 / users.jsonhttp:// localhost:3000 / user / 1.json页面, 这些页面均以 JSON和HTML格式呈现,没有“ .json”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM