Reputation: 1457
I have a bunch of possible options for the primary_category
for a blog
. Each has an associated icon, so I have them in a blogs/_category_icon.html.erb
partial:
<% case @blog.primary_category
when "General" %>
<%= link_to blogs_path, class: "text-slate" do %>
<i class="fas fa-book-open pr-2"></i> <%= @blog.primary_category %>
<% end %>
<% when "Motivation" %>
<%= link_to page_path("motivation"), class: "text-slate" do %>
<i class="fas fa-mountain pr-2"></i> <%= @blog.primary_category %>
<% end %>
<% when "Mindset" %>
<%= link_to page_path("mindset"), class: "text-slate" do %>
<i class="fas fa-brain pr-2"></i> <%= @blog.primary_category %>
<% end %>
<% when "Resourcing" %>
<%= link_to page_path("resourcing"), class: "text-slate" do %>
<i class="fas fa-first-aid pr-2"></i> <%= @blog.primary_category %>
<% end %>
<% when "Planning" %>
<%= link_to page_path("planning"), class: "text-slate" do %>
<i class="fas fa-sitemap pr-2"></i> <%= @blog.primary_category %>
<% end %>
<% when "Time Management" %>
<%= link_to page_path("time-management"), class: "text-slate" do %>
<i class="fas fa-stopwatch pr-2"></i> <%= @blog.primary_category %>
<% end %>
<% when "Discipline" %>
<%= link_to page_path("discipline"), class: "text-slate" do %>
<i class="fas fa-cookie-bite pr-2"></i> <%= @blog.primary_category %>
<% end %>
<% end %>
It renders perfectly on my blog#show
page with this:
<%= render "blogs/category_icon", locals: { blog: @blog } %>
However, when I try to call it on the blogs#index
page from within a <% @blogs.each do |blog| %>
block it's throwing up an error saying undefined method 'primary_category' for nil:NilClass
.
The code on the blogs#index
page is like this:
<% @blogs.each do |blog| %>
...
<%= render "blogs/category_icon", locals: { blog: blog } %>
...
<% end %>
Can anyone see why this local isn't getting passed through properly?
Upvotes: 1
Views: 360
Reputation: 33471
As stated in ActionView/PartialRenderer
, you need to use the partial
option:
<%= render partial: "blogs/category_icon", locals: { blog: blog } %>
Notice you can also use the option of rendering a collection of partials, but this time using a combination of collection
and as
options:
<%= render partial: "blogs/category_icon", collection: @blogs, as: :blog %>
The iteration through the elements of @blogs
is handled by Rails.
Upvotes: 4