views:

705

answers:

1

Hello,

I am building a site with works and their credits. What I am trying o achieve is to find each work's similar works based on the mutual titles in their credits.

I am adding each similar work into an array in a for loop and when I try to access the attributes of these works I get a "nil object when you didn't expect it!" error. I can see the Work objects when I debug in the array, but can't access to their attributes. Here is the code:

class Work < ActiveRecord::Base

  def similar_works
    @similar_works
  end

  def find_similar_works
    @similar_works = []
    for credit in self.credits
      same_credits = credit.title.credits #same credits with mutual titles
      for credit2 in same_credits
        @similar_works << credit2.work
        end
    end
  end

end



class WorksController < ApplicationController

  def index
    list
    render(:action => 'list')
  end

  def list
    # find similar works for each work
    @works.each do |work|
      work.find_similar_works
    end
  end

end



list.html

<% for work in @works -%>
<% for similarwork in work.similar_works%>
    <%= similarwork.name%> => nil object
    <%=debug(similarwork)%> => sample debug output is below
<% end %>
<% end %>



--- !ruby/object:Work 
attributes: 
  name: Borozan
  updated_at: 2009-07-31 12:30:30
  created_at: 2009-07-31 12:25:32
attributes_cache: {}

--- !ruby/object:Work 
attributes: 
  name: Boom
  updated_at: 2009-07-31 12:30:30
  created_at: 2009-07-31 12:25:32
attributes_cache: {}

--- !ruby/object:Work 
attributes: 
  name: Kamuflaj
  updated_at: 2009-07-31 12:30:30
  created_at: 2009-07-31 12:25:32
attributes_cache: {}
+1  A: 
  1. The variable is null, not its attribute.
  2. Paste the whole stack pls
  3. Paste the result of the following line: <%=debug(work.similar_works)%>
  4. It is possible to have a nil value in your array. Correct your function:

    def find_similar_works # .. do your stuff # then remove nil values @similar_works.compact! end

Vlad Zloteanu
Thank you very much vlad. @similar_work.compact! worked. Can you please explain why that problem occured in the first place? what did I miss, or didn't understand?Thanks
fahrio
You're welcome. It is because of this line: '@similar_works << credit2.work'. You do not check if every credit2 has a work, so you add nil values in the array. You can easyly debug with something like: puts "now adding work #{credit2.work} corresponding to credit #{credit2}".Please vote and mark the answer as the good one for you then :)
Vlad Zloteanu