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)

Alphabetical Index <% @letters.each do |letter| %> <% letter_class = (letter == @initial) ? "letter_current" : "letter" %>

<%= link_to letter, { :action => “index”, :id => letter },
:class => letter_class %>
<% end %>

<%= render :partial => “search” %>

And the partial, rendered by the index page:

<% if @users and not @users.empty? %>

<% @users.each do |user| %>
Name Gender Location
<%= link_to user.info.last_name, profile_for(user) %> <% end %>

<% 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.

On 21 February 2010 21:27, RubyonRails_newbie
[email protected] wrote:

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

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

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 - RDoc Documentation 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.