轨道3:什么是用JSON在铁轨REST-FUL行动响应的正确方法? [英] Rails 3: What is the proper way to respond to REST-ful actions with JSON in rails?
本文介绍了轨道3:什么是用JSON在铁轨REST-FUL行动响应的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让使用JSON响应的RESTful资源控制器我的Rails应用程序的API。这对我来说是全新的体验,所以我在寻找一些指导和指针。要开始做事了:
- 在Rails应用程序,什么是适当的方式与JSON响应REST-FUL控制器的方法呢? (创建,更新,销毁)
- 是否有一个惯用的方式,通过一个JSON响应,以指示成功/失败?
其他信息:
- 我目前正在轨工作3.0.beta2
- 我想避免使用插件或宝石做繁重的工作,我的目标是更好地了解如何使一个轨道3 API。
- 链接到的地方,我能找到的主题的更多信息也将是AP preciated,谷歌上的一些快速搜索并没有做我多好。
解决方案
#配置/ routes.rb中
MyApplicationsName :: Application.routes.draw做
资源:文章
结束#应用程序/控制器/ articles_controller.rb
类ArticlesController< ActionController的基地:: #使respond_with知道哪些格式
#允许在每个单独行动
respond_to代码:JSON 高清指数
@articles = Article.all
respond_with @articles
结束 高清节目
@article = Article.find(PARAMS [:ID])
respond_with @article
结束 ... DEF更新
@article = Article.find(PARAMS [:ID])
@ article.update_attributes(PARAMS [:文章]) #respond_with会自动检查@ article.valid?
#和适当回应... @ article.valid?将
#设置根据是否@ article.update_attributes
#得手过去所有的验证
#@如果article.valid?那么respond_with会重定向到
#到展示页面;如果!@article.valid~~V?然后respond_with
#将显示:编辑视图,包括@ article.errors
respond_with @article
结束 ...结束
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:
- In a rails application, what is the "proper" way to respond with JSON to REST-ful controller methods? (create, update, destroy)
- Is there an idiomatic way to indicate success/failure through a JSON response?
Additional information:
- I'm currently working with rails 3.0.beta2
- I would like to avoid using a plugin or gem to do the grunt work, my goal is to gain a better understanding of how to make a rails 3 API.
- Links to places I could find more information on the topic would also be appreciated, some quick searching on google didn't do me much good.
解决方案
#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
这篇关于轨道3:什么是用JSON在铁轨REST-FUL行动响应的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文