Rails 3:在rails中以REST方式响应JSON的正确方法是什么?

14

我正在尝试使用JSON响应RESTful资源控制器来为我的rails应用程序创建API。这对我来说是一个新的体验,因此我正在寻求一些指导和提示。首先:

  1. 在rails应用程序中,以JSON形式响应RESTful控制器方法(create,update,destroy)的“正确”方法是什么?
  2. 是否有一种惯用的方法通过JSON响应来表示成功/失败?

附加信息:

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

你解决了这个问题吗:“有没有一种惯用的方式通过JSON响应来表示成功/失败?” - David J.
我最近没有使用Rails,但从其他项目中看到的情况来看,在返回的JSON对象中使用布尔标志似乎是衡量JSON调用成功或失败的最直接方式。 - Damien Wilson
1个回答

29
#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,但不知怎么回事没能理解。这篇文章帮了我很多,感谢! - Damien Wilson
这是否意味着我们需要在视图中执行<% if @article.valid? %>逻辑? - dazonic
你需要在视图中编写逻辑来检查是否显示错误。但是我已经更新了我的答案,提供了更多信息。 - yfeldblum
关于响应销毁操作,您是只返回已删除对象的JSON还是仅发送带有200状态的标头? - Simon Polak
1
使用HTTP DELETE,您将返回状态码为204 No Content和空主体。 - yfeldblum
使用HTTP DELETE,对于HTML和浏览器,您还可以返回重定向到另一个页面,例如主页。 - yfeldblum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接