【问题标题】:Rails 3: What is the proper way to respond to REST-ful actions with JSON in rails?Rails 3:在 Rails 中使用 JSON 响应 REST-ful 操作的正确方法是什么?
【发布时间】:2011-02-04 01:55:20
【问题描述】:

我正在尝试使用对 RESTful 资源控制器的 JSON 响应为我的 rails 应用程序创建一个 API。这对我来说是一种新的体验,所以我正在寻找一些指导和指点。开始:

  1. 在 Rails 应用程序中,用 JSON 响应 REST-ful 控制器方法的“正确”方式是什么? (创建、更新、销毁)
  2. 是否有惯用的方式通过 JSON 响应指示成功/失败?

其他信息:

  • 我目前正在使用 rails 3.0.beta2
  • 我想避免使用插件或 gem 来完成繁重的工作,我的目标是更好地了解如何制作 rails 3 API。
  • 我可以找到有关该主题的更多信息的地方的链接也将不胜感激,在 google 上进行一些快速搜索对我没有多大帮助。

【问题讨论】:

  • 你有没有弄清楚这部分:“有没有一种惯用的方式来通过 JSON 响应来指示成功/失败?”
  • 我最近没有使用 Rails,但从我在其他项目中看到的情况来看,返回的 JSON 对象中的布尔标志似乎是衡量成功/失败的最直接方法JSON 调用。

标签: ruby-on-rails json api idioms ruby-on-rails-3


【解决方案1】:
#config/routes.rb
MyApplicationsName::Application.routes.draw do
  resources :articles
end

#app/controllers/articles_controller.rb
class ArticlesController < ActionController::Base

  # so that respond_with knows which formats are
  # allowed in each of the individual actions
  respond_to :json

  def index
    @articles = Article.all
    respond_with @articles
  end

  def show
    @article = Article.find(params[:id])
    respond_with @article
  end

  ...

  def update
    @article = Article.find(params[:id])
    @article.update_attributes(params[:article])

    # respond_with will automatically check @article.valid?
    # and respond appropriately ... @article.valid? will
    # be set based on whether @article.update_attributes
    # succeeded past all the validations
    # if @article.valid? then respond_with will redirect to
    # to the show page; if !@article.valid? then respond_with
    # will show the :edit view, including @article.errors
    respond_with @article
  end

  ...

end

【讨论】:

  • 正是我想要的,谢谢。我记得在 rails 文档中看到了respond_with,但由于某种原因它没有点击。这帮助很大,谢谢!
  • 这是否意味着我们需要在视图中执行&lt;% if @article.valid? %&gt; 逻辑?
  • 您需要视图中的逻辑来检查是否显示错误。但我用更多信息更新了我的答案。
  • 怎么响应销毁?您是只返回已删除对象的 json,还是只返回一个状态为 200 的标头?
  • 使用 HTTP DELETE,您将返回 204 No Content 的状态和一个空的正文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 2012-04-07
  • 1970-01-01
相关资源
最近更新 更多