简体   繁体   中英

Rails: Check if association exists on Model

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 if self.respond_to? user to the statement.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM