我想从自定义验证消息中删除该属性,只显示消息,而不是
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)
我该如何解决这个问题?
由于
修改
控制器
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
答案 0 :(得分:4)
full_message
需要两个参数attribute
和message
。
更新:避免猴子修补并编辑您的语言环境文件,例如:
en:
errors:
format: "%{message}"