Rails: Check if association exists on Model

1.3k views Asked by At

In a concern I run this code:

self.user&.favorite(self, scope: [:watching]) if self.respond_to? user
self.team&.user.favorite(self, scope: [:watching]) if self.respond_to? team

I included this concern in User & Team. Everytime I create a User, I get the following error:

NameError: undefined local variable or method `user' for #<User:0xb0e9020>

Same goes for creating a Team.

Why does this happen? Obviously User has no method (or equivalent) that responds to user on an instance. But thats why I added if self.respond_to? user to the statement.

1

There are 1 answers

0
Igor Drozdov On BEST ANSWER

Your problem is that respond_to? receives symbol as an argument

self.user&.favorite(self, scope: [:watching]) if self.respond_to? :user
self.team&.user.favorite(self, scope: [:watching]) if self.respond_to? :team

That's why if a user or team method is not defined, you'll receive the error.