0

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?

marcamillion
  • 32,933
  • 55
  • 189
  • 380

1 Answers1

1

It looks like you're using nested resources, so in the case of myapp.com/client/6/scores/new/ your new method in your ScoreController should be called.

In this method (or in a before filter), I'm assuming you have a line that's something like:

@client = Client.find(params[:client_id])

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 @clients or you could go ahead and rewrite your partial and split it up in if sections or so...

The error message you get basically means, that when ScoreController#new method's being rendered there's no object called @clients therefore it's nil, and the NilClass has no method collect

So I would just do the following in your ScoreController#new method:

# get your single client
@client = Client.find(params[:client_id])

# and simply put it in an array with the name your partial uses
@clients = [ @client ]

Now, I'm not sure that's an elegant solution, but it should keep you going...

Vapire
  • 4,568
  • 3
  • 24
  • 41