Reputation: 2380
I wanna achieve the following to display in rails app:
Product instance => "product"
ProductCustomer instance => "product customer"
so I could do
<%= 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 %>
At the moment I'm using the following which works in all cases:
p = Product.new
p.class.name.split(/(?=[A-Z])/).join(' ').downcase
pc = ProductCustomer.new
pc.class.name.split(/(?=[A-Z])/).join(' ').downcase
My problem is that it seems to be too complex. I guess there should be a better way. Any ideas?
Upvotes: 2
Views: 502
Reputation: 102036
Use ActiveModel::Naming instead. Its a wonderful API for getting stuff like human names, route keys and I18n keys from model classes or instances.
human(options={})
Transform the model name into a more humane format, using I18n. By default, it will underscore then humanize the class name.
placeholder: "Ask something about the #{ commentable.model_name.human }"
Note that you should provide <label>
elements for your inputs and not just placeholder attributes for accessibility.
In Rails you frequently use ActionView::Helpers::FormBuilder#label
:
<%= form_for([commentable, Comment.new]) do |f| %>
<%= f.label :body %>
<%= f.text_field :body %>
<% end %>
Which creates a label with a name
attribute tied to the ID of the input. However for this to work the Rails Way you need to let the form builder set the ID of the input.
For hiding elements I usually use the Zurb Foundation .show-for-sr
class which basically works like in the WAI tutorial:
.show-for-sr {
position: absolute !important;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
}
Upvotes: 6
Reputation: 1059
Yes you can do this: commentable.model_name.human
In Rails calling model_name
on an ActiveRecord model returns an instance of ActiveModel::Name which provides a useful api to interact with the model name.
Upvotes: 2