View related data during Iteration

Asked

Viewed 122 times

2

I created a relationship between the models client and content and I can access their data using the 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 the 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

3 answers

2


Hello @Rafael,

Problem is that in the log 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 the 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 higher than 2.3, an even cleaner way, using the Safe Navigation Operator (&.) :

@content = Content.all
@content.each do |content| 
   puts content.title
   puts content.target
   puts content.client&.name
end

1

  • the client has_many Contents and the contents belongs_to clients

0

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

If it is not possible to force so that all meet have clients, the ideal is to check for each record if client exists before trying to use name. An example:

puts content.client.name if content.client

Browser other questions tagged

You are not signed in. Login or sign up in order to post.