Add Button Assistant with I18n.t

I want to write an auxiliary button for sending, which takes into account the action (create or update) in order to get the correct translation. Here they are:

fr: submit: create: user: "Créer mon compte" product: "Déposer l'objet" session: "Se connecter" update: user: "Mettre à jour mon compte" product: "Modifier l'objet" 

I tried this:

 def submit_button(model) if model == nil I18n.t('submit.create.%{model}') else I18n.t('submit.update.%{model}') end end 

But that did not work, and rspec sent me the following:

 Capybara::ElementNotFound: Unable to find button ... 

I know the syntax problem, but I can not find how to make this work ...

+6
source share
3 answers

To do this, you do not need an assistant, you can achieve this with simple rails. The only thing you need is to order the I18n YAML correctly

 fr: helpers: submit: # This will be the default ones, will take effect if no other # are specifically defined for the models. create: "Créer %{model}" update: "Modifier %{model}" # Those will however take effect for all the other models below # for which we define a specific label. user: create: "Créer mon compte" update: "Mettre à jour mon compte" product: create: "Déposer l'objet" update: "Modifier l'objet" session: create: "Se connecter" 

After that, you only need to specify the submit button as follows:

 <%= f.submit class: 'any class you want to apply' %> 

Rails will take the shortcut you need for the button.

You can see more information about this here.

+12
source
 def submit_button(model) if model == nil I18n.t("submit.create.#{model}") else I18n.t("submit.update.#{model}") end end 

The% {} is used in the en.yml file when you send a local variable from a helper or view.

0
source

You need the model name, not the model object itself.

Try the following:

 def submit_button(model) model_name = model.class.name.underscore if model.new_record? I18n.t("submit.create.#{model_name}") else I18n.t("submit.update.#{model_name}") end end 

model must not be nil in the form.

0
source

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