Mike T
Mike T

Reputation: 4787

Render collection using a partial giving "undefined method for nil:NilClass"

I'm trying to render a collection of Projects using a project partial but I'm getting the following error:

undefined method `customer' for nil:NilClass
Extracted source (around line #1):
1: <p><%= company_name(@project) %><p>

The stacktrace is:

app/helpers/projects_helper.rb:4:in `company_name'
app/views/projects/_summary.html.erb:1:in
app/views/customers/index.html.erb:11:in

So, my index checks that their are projects to start with:

<% if @projects.any? %>
  <%= render :partial => "projects/summary", :collection => @projects %>
<% end %>

My partial (_summary.html.erb) is simply:

<p><%= company_name(@project) %><p>
<p><%= summary_description(@project) %><p>

and my ProjectsHelper company_name method is

def company_name(project)
  if project.customer.business_name.blank?
  ...Do stuff...

If I do the following via the rails console, it works fine:

projects.first.customer.business_name.blank?

I'm really confused because I thought that's what rendering a collection was supposed to do. Any help would be much appreciated.

Upvotes: 0

Views: 1757

Answers (2)

Mike T
Mike T

Reputation: 4787

I figured out what the problem was.

It was because I was using a differently-named partial to the model I was trying to render. I needed to just render a summary of the model, so I used a summary partial. In the partial though, the "name" of my project variable was "summary". So I changed my partial to:

<p><%= company_name(summary) %><p>
<p><%= summary_description(summary) %><p>

and it worked. Rails is still a mystery to me with stuff like this. From this post, the answer is to use: :as => :foo

<%= render :partial => "projects/summary", :collection => @projects, :as => :project %>

Upvotes: 1

Logan Serman
Logan Serman

Reputation: 29870

You should change your partial to

<p><%= company_name(project) %><p>
<p><%= summary_description(project) %><p>

See the Rails documentation about this under "Rendering Collections".

Upvotes: 3

Related Questions