DEV Community

Dmitry Voronov for JetRockets

Posted on • Originally published at jetrockets.pro

How to use Rails translations for Reform attributes

If you use Reform for the form objects and want the translations in your Rails application to work as with ActiveRecord objects, then you can add ActiveModel::Translation module to the form class or base class and specify the method with the key to translations.

class BaseForm < Reform::Form
  extend ActiveModel::Translation

  def self.i18n_scope
    :forms
  end
end
Enter fullscreen mode Exit fullscreen mode
class UserForm < BaseForm
  feature Coercion

  property :login
  property :change_password, virtual: true, type: Types::Form::Bool
  property :password
  property :password_confirmation

  validation do
    required(:login).filled
  end

  validation if: ->(_) { change_password } do
    required(:password).confirmation
  end
end
Enter fullscreen mode Exit fullscreen mode

Set translations for form fields.
You can move them to a new file config/locales/forms.yml.

en:
  forms:
    attributes:
      user_form:
        login: Enter login
        change_password: Change password?
        password: Enter password
        password_confirmation: Confirm password
Enter fullscreen mode Exit fullscreen mode

Now, translations will be used by the simple form or you can call them manually by UserForm.human_attribute_name.

Top comments (0)