Customise ActiveModel full_messages

◇◆丶佛笑我妖孽 提交于 2019-12-11 03:42:15

问题


I would like to remove the attribute from my custom validation messages and just display the message, so instead of

School Please Provide Your School Name

I want to return

Please Provide Your School Name

As set in my model here

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

The message gets returned as JSON response.

Looking at the full_messages method

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

Could I override this with

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

I have tried this

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

Located at /lib/active_model/errors.rb

but when i try to run my tests (rspec) I get the error

/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)

I load the file in my application.rb

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

How can i solve this please?

Thanks

EDIT

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

回答1:


full_message expects the two arguments attribute and message.

Update: Avoid monkey patching and edit your locale file to have something like:

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


来源:https://stackoverflow.com/questions/28985474/customise-activemodel-full-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!