6

我想为提交按钮编写一个助手,它考虑到获得正确翻译的操作(创建或更新)。他们来了 :

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"

我试过这个:

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

但它没有用,rspec 发给我:

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

我知道这是一个语法问题,但我不知道如何使这项工作......

4

3 回答 3

16

你不需要帮助,你可以用普通的轨道来实现它。您唯一需要做的就是正确订购您的 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"

之后,您只需要像这样定义提交按钮:

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

Rails 将获取按钮所需的标签。

您可以在此处查看有关它的更多信息

于 2013-08-15T15:06:20.377 回答
0

您需要模型的名称而不是模型对象本身。

尝试以下操作:

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形式上不得为 nil。

于 2013-06-07T08:02:23.847 回答
0
def submit_button(model)
  if model == nil
    I18n.t("submit.create.#{model}")
  else
    I18n.t("submit.update.#{model}")
  end
end

当您从帮助程序或视图发送局部变量时,在 en.yml 文件中使用 %{}。

于 2013-06-07T06:27:05.050 回答