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 %>
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 %>
Try putting the debug(similarwork) line before the similarwork.name
line. As you have it you will see the debug for all the good ones,
then the first nil one will cause the error and will not get to the
debug. That is a possibility anyway.
Also you could use ruby-debug to break in at that point and inspect
the whole set.
Can you give us a bit more info about what "credit.title.credits"
looks like? It looks like it should be an array of objects. Put a
logger.info similar_works.inspect and look at your development.log to
see what it says about the values it ends up with.
If it isn't an array or if it is an empty array you will just end up
doing nothing and that function just exits without accomplishing much.