Attribute Localization in Rails Virtual Models

I created a virtual (fickle) model in Rails 3 (see below)

Now I need to apply translations to the model, but the standard translation positions do not work. eg.

en: activerecord: attributes: media_upload: title: "My Title" 

I know that I can apply this directly to a label with an optional string parameter, for example. f.label :title, t('activerecord.attributes.media_upload') , but this does not work for error messages as a result of checks. Similarly, I could add a key to the translation file for the label helper, as suggested in Localize a nested virtual attribute in Rails , but this also does not work for validation.

 helpers: label: media_upload: title: "My Title" 

Besides overriding all relevant validation statements, is there another way to localize attributes in mutable models?

Below is a sample model,

 class MediaUpload include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :media_file, :title validates_presence_of :media_file validates_presence_of :title def initialize(attributes = {}) unless attributes.nil? attributes.each do |name, value| send("#{name}=", value) end end end def persisted? false end end 
+4
source share
2 answers

You need to write like this:

 en: activemodel: attributes: media_upload: title: "My Title" 

not activerecord replace it with activemodel

+5
source

It seems you are using the simple_form pearl to generate forms.

So, following the i18n chapter from github , your internationalization file should look like this

 en: simple_form: labels: media_upload: media_file: My File title: My Title 

If you are using Rails 4, there is an easier way to make ActiveModel Form Objects . You can simply include ActiveModel::Model to do so

 class MediaUpload include ActiveModel::Model attr_accessor :media_file, :title validates_presence_of :media_file validates_presence_of :title end 
0
source

Source: https://habr.com/ru/post/1502946/


All Articles