Archive

Posts Tagged ‘i18n’

Form label should use I18n

June 15th, 2010 yakjuly No comments

f.label方法 rails默认只显示名称,实际上让label text显示位 I18n中的 active_record.human_attribute_names 翻译才是正确的.

f.label(:name) 应该等效于 f.label(:name, t(:name))

class ActionView::Helpers::InstanceTag

  def to_label_tag(text = nil, options = {})
    options = options.stringify_keys
    tag_value = options.delete("value")
    name_and_id = options.dup
    name_and_id["id"] = name_and_id["for"]
    add_default_name_and_id_for_value(tag_value, name_and_id)
    options.delete("index")
    options["for"] ||= name_and_id["id"]
    content = if text.blank?
      key = :"active_record.human_attribute_names.#{object.class.name.underscore.to_sym}.#{method_name}"
      I18n.translate(key, :default => object.class.human_attribute_name(method_name))
    else
      text.to_s
    end
    label_tag(name_and_id["id"], content, options)
  end

end

这样写的缺点是表单中的f.object必须有值,所以form_for就不能写成

form_for :user, :url => users_path do |f|

而必须给其一个实例

form_for :user, @user, :url => users_path do |f|

不过你也可以再改写to_label_tag方法,将object.class改为object_name.to_s.camelize.这样就不用给出实例也能翻译了。

Categories: rails Tags: ,