Rails 5 Basics : View Duplication
- Learn how to eliminate duplication in views by using partials.
Look at the app/views/new.html.erb and app/views/edit.html.erb. There is duplication.
Create a file called
app/views/articles directory with the following contents:
<%= form_for @article do |f| %> <p> <%= f.label :title %><br> <%= f.text_field :title %> </p> <p> <%= f.label :description %><br> <%= f.text_area :description %> </p> <p> <%= f.submit %> </p> <% end %>
app/views/articles/new.html.erb and change the content as follows:
<h1>New Article</h1> <%= render 'form' %>
app/views/articles/edit.html.erb and change the content as follows:
<h1>Edit Article</h1> <%= render 'form' %>
http://localhost:3000/articles and create new article and edit existing article. The name of the partial begins with an underscore, when you include the partial by using the render helper you don't include the underscore. This is the Rails convention for using partials.
If you get the missing partial error. It means you did not create the
app/views/articles/_form.html.erb file. Make sure you followed the instruction in step 2.
In this lesson we saw how to eliminate duplication in views by using partials. In the next lesson we will learn about relationships between models.
Ace the Technical Interview
- Easily find the gaps in your knowledge
- Get customized lessons based on where you are
- Take consistent action everyday
- Builtin accountability to keep you on track
- You will solve bigger problems over time
- Get the job of your dreams
Take the 30 Day Coding Skills Challenge
Gain confidence to attend the interview