gpt4 book ai didi

ruby-on-rails - ActiveModel::Errors:Class 的未定义方法 `model_name'

转载 作者:行者123 更新时间:2023-12-03 02:16:43 25 4
gpt4 key购买 nike

我有以下 mongoid 模型类:

class Exercise
include Mongoid::Document
field :name, :type => String
field :description, :type => String

belongs_to :group

validates_presence_of :name, :description, :group
end

我有以下 Controller :

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 respond_with 帮助器期望接收 Rails 模型对象作为第一个参数。因此,在这种情况下,您只需要 respond_with @exercise, status: :unprocessable_entity 然后在您的响应 View 中,您需要正确格式化错误数据,我假设您是通过 ajax 执行此操作并使用 json 等进行响应。希望有帮助。

关于ruby-on-rails - ActiveModel::Errors:Class 的未定义方法 `model_name',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11592185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com