Submit button helper with I18n.t

ぐ巨炮叔叔 提交于 2019-12-18 06:06:14

问题


I want to write a helper for a submit button, that takes in account the action (create or update) to get the right 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 it didn't worked and rspec send me that :

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

I know that's a syntactical problem, but I don't find how to make this work...


回答1:


You don't need a helper for that, you can achieve it with plain rails. The only thing you need is to properly order your I18n YAML

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 define your submit button like this:

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

Rails will take the label you need for the button.

You can see some more info about it here




回答2:


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

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




回答3:


You need the name of the model 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 a form.



来源:https://stackoverflow.com/questions/16977371/submit-button-helper-with-i18n-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!