加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 3:在rails中使用JSON响应REST动作的正

发布时间:2020-12-16 20:41:39 所属栏目:百科 来源:网络整理
导读:我试图为我的rails应用程序使用JSON响应到RESTful资源控制器.这对我来说是一个新的经历,所以我正在寻找一些指导和指导.要开始: 在rails应用程序中,使用JSON对REST控制器方法进行响应的“正确”方式是什么? (创建,更新,销毁) 有没有一个惯用的方式来表示通
我试图为我的rails应用程序使用JSON响应到RESTful资源控制器.这对我来说是一个新的经历,所以我正在寻找一些指导和指导.要开始:

>在rails应用程序中,使用JSON对REST控制器方法进行响应的“正确”方式是什么? (创建,更新,销毁)
>有没有一个惯用的方式来表示通过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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读