加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 用于ActiveModel :: Errors的未定义方法`model

发布时间:2020-12-17 02:13:38 所属栏目:百科 来源:网络整理
导读:我有以下mongoid模型类: class Exercise include Mongoid::Document field :name,:type = String field :description,:type = String belongs_to :group validates_presence_of :name,:description,:groupend 我有以下控制器: class ExercisesController A
我有以下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)

我收到以下错误

undefined method `model_name’ for ActiveModel::Errors:Class

填充了错误集合,因此我认为我的respond_with语法错误.

解决方法

rails_with helper的rails期望接收rails模型对象作为第一个参数.所以在这种情况下你只需要response_with @exercise,status :: unprocessable_entity然后在你的响应视图中你需要正确格式化错误数据,我假设你是通过ajax做这个并用json响应等.希望有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读