0

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 Answer 1

2
  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

Sign up to request clarification or add additional context in comments.

2 Comments

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
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.