DEV Community

Dmitry Voronov for JetRockets

Posted on • Originally published at jetrockets.pro

4 1

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.

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spirits—leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay