【问题标题】:Rails return JSON instead of HTMLRails 返回 JSON 而不是 HTML
【发布时间】:2015-11-16 18:40:19
【问题描述】:

我有一个 ruby​​ on rails Web 应用程序,但我希望它像 Web 服务一样运行,而不是 HTML 来返回 JSON。我希望所有 CRUD 方法都使用这个。我希望将整个页面呈现为 JSON,到目前为止,我只在 User 变量的 Show and Edit 中实现了这一点。但我希望整个页面,所有 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

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

编辑:如果我在 routes.rb 中添加类似 resources :users, defaults: {format: :json} 的内容,则会收到错误消息“缺少模板用户/索引、应用程序/索引与 {:locale=>[:en], :formats=>[ :json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}"

【问题讨论】:

    标签: html ruby-on-rails json rest crud


    【解决方案1】:

    尝试索引页面

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

    对于所有其他的,用户是一个对象

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

    在此之后,您将拥有 http://localhost:3000/users.jsonhttp://localhost:3000/user/1.json 页面,它们呈现为没有“.json”的 JSON 和 HTML

    【讨论】:

    • 是否可以在不专门在 URL 中调用 .json 的情况下进行 JSON 渲染?例如localhost:3000/users 所以它会自动显示 JSON?
    • 所以如果你只需要 JSON,你必须像你意识到的那样做。在您编写资源的路线中:用户,默认值:{format:'json'}。并在控制器中渲染 json:@user 或 @users。如果没有帮助,只需在控制台中显示本地服务器返回的内容
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2017-03-28
    • 2019-03-31
    相关资源
    最近更新 更多