将模型的名称添加到Rails中的字符串

Sea*_*yar 1 ruby ruby-on-rails

我想在rails app中显示以下内容:

Product instance => "product"
ProductCustomer instance => "product customer"
Run Code Online (Sandbox Code Playgroud)

所以我能做到

<%= form_for([commentable, Comment.new]) do |f| %>
  <%= f.text_field :body, class: "form-control", id: "comment-text-area-#{commentable.id}", 
    placeholder: "Ask something about the #{commentable.class.name.split(/(?=[A-Z])/).join(' ').downcase }" %>
  ......
<% end %>
Run Code Online (Sandbox Code Playgroud)

目前我正在使用以下适用于所有情况的:

p = Product.new
p.class.name.split(/(?=[A-Z])/).join(' ').downcase

pc = ProductCustomer.new
pc.class.name.split(/(?=[A-Z])/).join(' ').downcase
Run Code Online (Sandbox Code Playgroud)

我的问题是它看起来太复杂了.我想应该有更好的方法.有任何想法吗?

max*_*max 5

请改用ActiveModel :: Naming.它是一个很棒的API,用于从模型类或实例中获取人名,路由键和I18n键等内容.

human(options={})
使用I18n将模型名称转换为更人性化的格式.默认情况下,它会下划线然后将类名人性化.

placeholder: "Ask something about the #{ commentable.model_name.human }"
Run Code Online (Sandbox Code Playgroud)

请注意,您应该为<label>输入提供元素,而不仅仅是可访问性的占位符属性.

标签:

在Rails中你经常使用ActionView::Helpers::FormBuilder#label:

<%= form_for([commentable, Comment.new]) do |f| %>
  <%= f.label :body %>
  <%= f.text_field :body %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

这会创建一个标签,其name属性与输入的ID相关联.但是,要使用Rails Way,您需要让表单构建器设置输入的ID.

对于隐藏元素,我通常使用Zurb Foundation .show-for-sr类,它基本上像在WAI教程中一样工作:

.show-for-sr {
  position: absolute !important;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)