_form.html.erb
.render
method, like so: <%= render 'form' %>
. This will look for a file named _form.html.erb
in the same directory as the view from where it's being called.<%= render 'form', local_variable: @instance_variable %>
.field_with_errors
. You can customize this to display error messages to users.Create a file named _form.html.erb
in the app/views/users
directory and add the following code:
<%= form_with(model: user, local: true) do |form| %>
<% if user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name, id: :user_name %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
In your new.html.erb
and edit.html.erb
views for the User model, you can now render the form like this:
<%= render 'form', user: @user %>
new
and edit
views.Solution:
_comment_form.html.erb
in app/views/comments
and add your form code.new.html.erb
and edit.html.erb
, add <%= render 'comment_form', comment: @comment %>
.Exercise: Display a list of error messages in a partial view.
_errors.html.erb
in app/views/shared
and add code to display error messages.<%= render 'shared/errors', object: @object %>
.Remember to practice regularly and revisit these concepts to solidify them in your memory. Happy coding!