logo       

[Rails] Re: Cannot access an objectâs attributes in an array: msg#03301

RubyonRailsTalk

Subject: [Rails] Re: Cannot access an objectâs attributes in an array


2009/7/31 fahrio <fahrio@xxxxxxxxx>:
>
> 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 %>
>
>

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.

Colin

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

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@xxxxxxxxxxxxxxxx
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@xxxxxxxxxxxxxxxx
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Google Custom Search

News | Mail Home | sitemap | FAQ | advertise