Inconsistent noMethod error...

Hi There,

I'm following a tutorial to introduce a search feature.

It comprises of a series of boxes, (A-Z) which are links. These links when clicked, trigger the search code in index (in infocontroller.rb)

Code below:

Info Controller:   def index

  @title = "search"

  @letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")     if params[:id]       @initial = params[:id]       infos = Info.find(:all,                         :conditions => ["last_name like ?", @initial +'%'],                         :order => "last_name")     @users = infos.collect { |info| info.user }     end   end

The index page (where the search is performed) <fieldset> <legend>Alphabetical Index</legend> <% @letters.each do |letter| %> <% letter_class = (letter == @initial) ? "letter_current" : "letter" %>

<%= link_to letter, { :action => "index", :id => letter }, :class => letter_class %> <% end %> <br clear="all" /> </fieldset>

<%= render :partial => "search" %>

And the partial, rendered by the index page:

<% if @users and not @users.empty? %> <table class="users" border="0" cellpadding="5" cellspacing="1">

  <tr class="header">   <th>Name</th> <th>Gender</th> <th>Location</th>   </tr>   <% @users.each do |user| %>

  </td>

  <td><%= link_to user.info.last_name, profile_for(user) %>

  </tr>   <% end %>   </table>

  <% end %>

For some odd reason, when I click the letter 'B' It throws an exception: You have a nil object when you didn't expect it! The error occurred while evaluating nil.info

however, if I select any other letter, I have no problems.

What's going on?

Many Thanks

The only place .info is being called is here: <%= link_to user.info.last_name, profile_for(user) %> @users must contain a nil object.

Looks like you may have an info record with last_name beginning with B, that does not have a user (user_id == nil)

Maybe you have added the Info-Table after you have already put some Data in your User-table. In this case, there can exist some resultsets without an info-part.

That's not an inconsistent nomethod error... if *every* time you click "B" it throws, it's a *very* consistent one!

It's telling you, right there on the screen, that one of the values in the @users array is nil, and nil objects don't have an "info" method.

Have a rummage through the methods for Array [1] when you have downtime, and spot what the "compact" method does... I think it'll sort you out (if you amend your controller thus :slight_smile:

@users = infos.collect { |info| info.user }.compact

[1] Class: Array (Ruby 3.1.2) Whenever I get stuck, I'm straight onto Google with "ruby api [classname]" to bring me straight to the reference page that should get me on the right track again ("sometime it's "Rails api [classname/methodname]" if the thing I'm messing with isn't pure Ruby.