Rails 3:在 Rails 中使用 JSON 响应 REST-ful 操作的正确方法是什么? [英] Rails 3: What is the proper way to respond to REST-ful actions with JSON in rails?

查看:26
本文介绍了Rails 3:在 Rails 中使用 JSON 响应 REST-ful 操作的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make an API for my rails application using JSON responses to RESTful resource controllers. This is a new experience for me, so I'm looking for some guidance and pointers. To start things off:

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

<小时>

其他信息:

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

推荐答案

#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 3:在 Rails 中使用 JSON 响应 REST-ful 操作的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆