Display related data during Iteration

2

I have created a relationship between the client and content models and I can access their data using console normally.

con = Content.find(1)
con.client.name # Nome do cliente

But when I try to access this data during a loop, I get the error that name has not been set / does not exist.

@content = Content.all
@content.each do |content| 
   puts content.title
   puts content.target
   puts content.client.name # O erro acontece aqui
  

undefined method 'name' for nil: NilClass

    
asked by anonymous 28.09.2016 / 20:17

3 answers

2

Hello @Rafael,

Problem is that in the record you searched on the console client exists, but during the loop one of the records does not have a client related generating error. There are several ways to solve one of them is to use try (for versions prior to ruby 2.3 :

@content = Content.all
@content.each do |content| 
   puts content.title
   puts content.target
   puts content.client.try(:name)
end

Or for versions greater than 2.3 , an even cleaner mode, using Safe Navigation Operator (&.) :

@content = Content.all
@content.each do |content| 
   puts content.title
   puts content.target
   puts content.client&.name
end
    
29.09.2016 / 01:39
1

The error explicitly states that content.client is not initialized.

How was the relationship created?

In this case: client belongs_to content and: content has_one client

And in migrations map the referenced resource.

source: link

    
28.09.2016 / 21:36
0

This error means that the nil class does not contain the name method. This is because some of your content has no associated client, then content.client returns nil, and content.client.name returns the reported error because you are trying to use the name method in the nil class.

If you can not force all contents to have clients , you should check for each record if client exists before trying use name . An example:

puts content.client.name if content.client
    
28.09.2016 / 22:27