Forum: Ruby on Rails type mismatch because of misled array index

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Mike S. (Guest)
on 2006-01-23 03:01
Most times I look up a list of books I want to know a page reference for
each one, so the views that display booklists expect an array of
two-element arrays, constructed via a method in the model like so:
(class Category)
  def book
    @book =
    self.bookshelves.each { |x| @book << [, x.pages] }
    return @book

When I get the list of all books that a user has listed, I have no page
numbers in that table, nor do I want any.  I tried to fill the second
slot with nils or empty strings, since that what x.pages would be for a
book with no page reference anyway.
(class User)
  def book
    @books = []
    self.books.each { |b| @books << [b, nil] }
    return @books

But when I call that method in my controller,

when 'user'
      @books = User.find(params[:id]).book

I get this error:

ActiveRecord::AssociationTypeMismatch in View#bookslist

Book expected, got NilClass
RAILS_ROOT: /Volumes/TRAVELDRIVE/sandcastle/script/../config/..

Application Trace | Framework Trace | Full Trace
#{RAILS_ROOT}/app/models/user.rb:106:in `book'
#{RAILS_ROOT}/app/models/user.rb:106:in `each'

I changed the nil in to '', and it said "Book expected, got
String", so it's clear that it is referring to the second argument
there.  But I don't even see how it knows to 'expect' a book from that
context.  If I change to put a book in the second array slot,
like so:

    self.books.each { |b| @books << [b, b] }

then WEBrick starts churning up as much of my cpu as it can get
(60-70%), and mysqld also gets quite a workout (3% of cpu).

My suspicion is that I've once again run afoul of some reserved words,
because equivalent code seems to work elsewhere.

This topic is locked and can not be replied to.