1
votes

I want to provide a useful :length validation message that tells the user how long the current value is. Instead of "Please limit your message to 100 characters," I want to say, "Please limit your message to 100 characters; you currently have 152 characters."

However, it doesn't appear that Rails i18n makes the record itself available for introspection when translating the error message. Is there any way to achieve an i18n message like the following for an ActiveRecord model?

too_long: "Maximum %{count} characters. You currently have %{value.length} characters."

When I do this, Rails refuses to interpolate "%{value.length}" and just passes it through.

1

1 Answers

1
votes

I think it may help you:

# models/record.rb
class Record < ApplicationRecord
  validates :field, length: { 
    maximum: MAXIMUM_CHARS,
    too_long: I18n.t("errors.messages.too_long",
                count: MAXIMUM_CHARS, current_length: @record.title.length) }
end

# en.yml
too_long: "Maximum %{count} characters. You currently have %{current_length} characters."