This is the relevant part of my _form.html.erb
<%= form_for(@score) do |f| %>
<% if @score.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@score.errors.count, "error") %> prohibited this score from being saved:</h2>
<ul>
<% @score.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :client_id %><br />
<%= f.select :client_id, @clients.collect { |c| [c.name, c.id] }, {:include_blank => 'None'} %>
</div>
<div class="field">
<%= f.label :firm_size %><br />
<%= f.text_field :firm_size %>
</div>
.
.
.
<div class="actions">
<%= f.submit %>
</div>
<% end %>
This partial works when I have a generic for creating a Score and there is a collection of clients passed in through the controller via clients.
The issue is when there is just one client record….say for a URL like:
myapp.com/client/6/scores/new/
Given that I have a client_id in the params, it gives me a nil error:
undefined method `collect' for nil:NilClass
How do I solve this for one single @client record?
It looks like you’re using nested resources, so in the case of
myapp.com/client/6/scores/new/yournewmethod in yourScoreControllershould be called.In this method (or in a before filter), I’m assuming you have a line that’s something like:
Now, if you want to use your partial the way yours is built, you either have to ensure, that there’s an object that responds to the method
collect(i.e. an array) with the name of@clientsor you could go ahead and rewrite your partial and split it up inifsections or so…The error message you get basically means, that when
ScoreController#newmethod’s being rendered there’s no object called@clientstherefore it’s nil, and theNilClasshas no methodcollectSo I would just do the following in your
ScoreController#newmethod:Now, I’m not sure that’s an elegant solution, but it should keep you going…