问题
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