logo       

[Rails] Re: Cannot access an object’s attributes in an array: msg#03309

RubyonRailsTalk

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


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.

On Jul 31, 11:35 am, fahrio <fah...@xxxxxxxxx> wrote:
> 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: {}
--~--~---------~--~----~------------~-------~--~----~
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