fahrio
fahrio

Reputation: 109

Ruby on Rails : Cannot access an object's attributes in an array

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: {}

Upvotes: 0

Views: 2486

Answers (1)

Vlad Zloteanu
Vlad Zloteanu

Reputation: 8512

  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

Upvotes: 2

Related Questions