Rails 3: What is the proper way to respond to REST-ful actions with JSON in rails?

可紊 提交于 2019-11-27 00:15:22

问题


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. In a rails application, what is the "proper" way to respond with JSON to REST-ful controller methods? (create, update, destroy)
  2. 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.

回答1:


#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


来源:https://stackoverflow.com/questions/2572571/rails-3-what-is-the-proper-way-to-respond-to-rest-ful-actions-with-json-in-rail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!