有几种方法可以解决这个问题。下面解释的方法适用于 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
给猫剥皮的方法总是不止一种。我希望这会有所帮助