Reputation: 2772
I'm using locale to configure error messages coming from my Rails API server, was wondering if there is anyway to also attach HTTP status codes?
For instance:
say I have a model:
email.rb
class Email < ApplicationRecord
validates_presence_of :email_address
validates :email_address, allow_blank: true, format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: {case_sensitive: false }
end
I have the config set up like so:
en.yml
en:
activerecord:
attributes:
email:
email_address: Email address
errors:
messages:
record_invalid: "%{errors}"
# I want to do something like this
blank:
message: is required.
status_code: 422
taken:
message: is already taken.
status_code: 409
Programmatically is fine too, I just want to return the appropriate HTTP status code, 422, 409, 404, 401 etc. when applicable.
Thanks in advance!
Upvotes: 0
Views: 507
Reputation: 21015
To do what you want, which I don't recommend
You'll need to write some extra code, the default behavior is 422, to change it, you can add code that asks what errors does the model has a respond accordingly, or figure out a way to monkey patch the built in rails code that responds with 422.
see relevant rails code line 25
Anyway it's a bit of code smell (what you are currently trying to achieve), the model should not be aware of anything related to HTTP, so maybe the translation isn't the proper place for status codes (it wouldn't change if you are on another human spoken language)
Upvotes: 1