gpt4 book ai didi

ruby-on-rails - 自定义 ActiveModel full_messages

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:17 24 4
gpt4 key购买 nike

我想从我的自定义验证消息中删除该属性并只显示该消息,而不是

School Please Provide Your School Name

我想回去

Please Provide Your School Name

在我这里的模型中设置

validates :school, presence: { message: 'Please Provide Your School Name' }

消息作为 JSON 响应返回。

查看 full_messages 方法

# File activemodel/lib/active_model/errors.rb, line 348
def full_messages
map { |attribute, message| full_message(attribute, message) }
end

我可以用

覆盖它吗
# File activemodel/lib/active_model/errors.rb, line 348
def full_messages
map { |attribute, message| full_message(message) }
end

我试过了

module ActiveModel
class Errors
def full_messages
map { |attribute, message| full_message(message) }
end
end
end

位于 /lib/active_model/errors.rb

但是当我尝试运行我的测试(rspec)时我得到了错误

/home/richardlewis/.rvm/gems/ruby-2.2.0@lnf_api/gems/activemodel-4.2.0/lib/active_model/validations.rb:297:in `initialize': wrong number of arguments (1 for 0) (ArgumentError)

我将文件加载到我的 application.rb

config.autoload_paths += %W(#{config.root}/lib)

请问我该如何解决?

谢谢

编辑

Controller

class RegistrationsController < Devise::RegistrationsController
skip_before_action :verify_authenticity_token
respond_to :json

def create
@user = User.new(registration_params)
if @user.valid?
@user.save
render json: { message: I18n.t("devise.registrations.signed_up_but_unconfirmed") }, status: 201
else
render json: { message: @user.errors.full_messages }, status: :unprocessable_entity
end
end

protected
def registration_params
json_params = ActionController::Parameters.new(JSON.parse(request.body.read))
json_params.require(:user).permit(:username, :school, :email, :password, :password_confirmation)
end
end

最佳答案

full_message 需要两个参数 attributemessage

更新:避免猴子修补并编辑您的语言环境文件以使其具有如下内容:

en:
errors:
format: "%{message}"

关于ruby-on-rails - 自定义 ActiveModel full_messages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28985474/

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