validation - Creating better error messages in the View for Rails -
i experimenting simple people/new page practice showing error messages. right now, below set-up, error messages display okay little awkward because text says "firstname can't blank", "lastname can't blank" , forth. want text "first name can't blank" , "last name can't blank" (with spaces), i'm assuming error messages following attribute names defined in model, , there's no way change explicitly.
so how can change that? can not achieve change without making changes particular partial? (shared_error_messages)
thanks, screenshot of new view below.
people_controller.rb
class peoplecontroller < applicationcontroller def new @person = person.new @people = person.all end def create @person = person.new(person_params) if @person.save redirect_to new_person_path else render 'new' end end private def person_params params.require(:person).permit(:firstname, :lastname, :age) end end
person.rb
class person < activerecord::base validates :firstname, presence: true, length: {maximum: 15}, format: { with: /\a[a-za-z]+\z/, message: "only allows letters" } validates :lastname, presence: true, length: {maximum: 15}, format: { with: /\a[a-za-z]+\z/, message: "only allows letters" } validates :age, presence: true, length: {maximum: 3} end
new.html.erb
enter information <hr> <%= form_for @person |f| %> <%= render 'shared/error_messages', object: f.object %> first name: <%= f.text_field :firstname %><br> last name: <%= f.text_field :lastname %><br> age: <%= f.number_field :age %><br> <%= f.submit "see life clock" %> <% end %>
shared/_error_messages
<% if object.errors.any? %> <div id="error_explain"> <h2><%= pluralize(object.errors.count, "error") %> prohibited being saved db</h2> <ul> <% object.errors.full_messages.each |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %>
assuming you're using rails 3.2 or later, "best" way localization. edit en.yml file , add this:
en: activerecord: attributes: person: firstname: "first name" lastname: "last name"
the error reporting system human-friendly names attributes localization file. thie may seem heavy-handed, in opinion best way because these names accessible anywhere, centralized, , easy maintain.
if need friendly name in own code, (for example, in label on edit form or column header in list table) can access this:
person.human_attribute_name(:firstname)
now if change en.yml, change reflect throughout site. , should ever need localize language, you're on right track already.
if you, can change validations have complete sentences messages, , change _error_messages partial this:
<% if object.errors.any? %> <div id="error_explain"> <h2><%= pluralize(object.errors.count, "error") %> prohibited being saved db</h2> <ul> <% object.errors.each |attr, msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %>
Comments
Post a Comment