Since having made so many partials to may app upon creation, it has saved me so much time in updating it, that I felt I should take a few minutes that I gained to write a post on how useful it is, so maybe you will utilize this super easy and handy tool.
On my Recipe App that I made on Ruby on Rails, anything that can be used in multiple places were rendered as a partial.
These same lines were rendered on user show pages, recipe show pages, and index pages. In fact my smallest partial was simply an image of a heart!
Aside from all the work in getting my app to work, and function correctly, have links with proper routes and forms that would submit, I would only have to worry about it once, because it was only in my views once — they were using the same partial.
And when I later implemented JavaScript and Jquery and hijacked links and forms, when I did it in one place, it worked on the whole site. It’s tough enough working with AJAX requests and JQuery/Javascript functions, I don’t need the extra work by having to enter many views to make sure classes and ID’s are always correct.
Here is an example of a partial that was used:
Recipe#Show
1
2
3
4
5
6
7
8
9
|
<%= render 'recipes/recipe_details', recipe: @recipe %>
<div>
<%= render 'comments/list_comments', comments: @recipe.comments if @recipe.comments %>
</div>
<br />
<div id="comments">
Add your comment below! (You must be signed in)
<%= render 'comments/form', comment: @recipe.comments.new, recipe: @recipe%>
</div>
|
We’ll follow the Recipe Details to recipe_details:
1
2
3
4
5
6
7
8
9
10
11
12
|
<h1><%= recipe.name %></h1>
<h2><%= recipe.time_in_minutes %> minutes until it's ready | By: <%= link_to recipe.user_name, user_path(recipe.user)%></h2>
<%= render 'favorites/favorited', recipe: recipe%>
<%= render 'ingredients/list_ingredients', recipe: recipe %>
<h4><%= recipe.instructions %></h4>
<%= link_to "Edit", edit_recipe_path(recipe) if logged_in? && current_user.can_edit?(recipe)%>
<%= link_to "Delete", recipe_path(recipe), method: :delete if logged_in? && current_user.can_delete?(recipe)%>
|
Which then pulls in 2 more partials, one for the favorite icon (our smallest partial), and one for ingredients:
favorites/favorited partial:
1
2
3
4
5
6
7
8
9
10
|
<% if current_user && recipe.favorite?(current_user) %>
<span class="favorites favorited">
<%= link_to image_tag("heart-red.png"), "#", :data => {:recipe => recipe.id }%>
</span>
<% else %>
<span class="favorites favorite">
<%= link_to image_tag("heart.png"), "#", :data => {:recipe => recipe.id }%>
</span>
<% end %>
|
ingredients/list_ingredients partial:
1
2
3
4
5
|
<ul>
<% recipe.recipe_ingredients.each do |recipe_ingredient| %>
<li><%= "#{recipe_ingredient.quantity} #{recipe_ingredient.ingredient.name}" %></li>
<% end %>
</ul>
|
I hope this will inspire you to keep making partials as details as necessary!