代码之家  ›  专栏  ›  技术社区  ›  Damien Wilson

Rails3:在Rails中使用JSON响应RESTful操作的正确方法是什么?

  •  14
  • Damien Wilson  · 技术社区  · 14 年前

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

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

    其他信息:

    • 我目前正在使用Rails 3.0.beta2
    • 我想避免使用插件或gem来完成咕噜的工作,我的目标是更好地了解如何制作Rails3API。
    • 链接到我能找到更多关于这个话题的信息的地方也会被感激,一些在谷歌上快速搜索对我没有太大帮助。
    1 回复  |  直到 12 年前
        1
  •  29
  •   Michael Durrant    12 年前
    #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