我有以下mongoid模型类:
class Exercise
include Mongoid::Document
field :name, :type => String
field :description, :type => String
belongs_to :group
validates_presence_of :name, :description, :group
end
我有以下控制器:
class ExercisesController < ApplicationController
respond_to :json
def create
@exercise = Exercise.create(params[:exercise])
if @exercise.save
respond_with @exercise
else
respond_with(@exercise.errors, :status => :unprocessable_entity)
end
end
end
该模型在有效时保存良好,但当运行以下行时:
respond_with(@exercise.errors, :status => :unprocessable_entity)
我得到以下错误
ActiveModel:的未定义方法"model_name":错误:类
error集合已填充,所以我认为responsd_with语法是错误的。
rails responsed_with-helper希望接收一个rails模型对象作为第一个参数。所以在这种情况下,你只需要responsd_with@exercise,status::unprocessable_entity,然后在你的响应视图中,你需要正确格式化错误数据,我假设你是通过ajax和json等进行响应的。希望这会有所帮助。