有几种方法可以解决这个问题。该方法如下解释是为Rails 3.1
呼叫在你的方法直接呈现(这种做法是一个JSON API唯一的方法帮助的,因为HTML渲染将是不存在的。):
def newItem
@Item = Item.create(:description => params[:description], :type_id => params[:type])
render json: @Item
end
使用respond_do块:
def newItem
@Item = Item.create(:description => params[:description], :type_id => params[:type])
respond_to do |format|
if @Item.save
format.html { redirect_to @Item, notice: 'Item was successfully created.' }
format.json { render json: @Item, status: :created, location: @Item
else
format.html { render action: "new" }
format.json { render json: @Item.errors, status: :unprocessable_entity }
end
end
end
教你的控制器的响应格式,你的愿望:
class ContributionsController < ApplicationController
# Set response format json
respond_to :json
...
def newItem
@Item = Item.create(:description => params[:description], :type_id => params[:type])
respond_with @Item #=> /views/contributions/new_item.json.erb
end
可能的“疑难杂症” ......
如果验证失败的项目创建,你不会得到的ID后面,也不会报告故障(比HTTP响应代码等)
添加以下你的模型。它将在json响应中包含验证失败的错误哈希值
class Item < ActiveRecord::Base
...
# includes any validation errors in serializable responses
def serializable_hash(options = {})
options = { :methods => [:errors] }.merge(options ||= {})
super options
end
永远有不止一种方式来为猫皮肤。我希望这可以帮助