Ruby on rails Rails:检查模型上是否存在关联
在一个问题中,我运行以下代码:Ruby on rails Rails:检查模型上是否存在关联,ruby-on-rails,ruby,model,associations,activesupport-concern,Ruby On Rails,Ruby,Model,Associations,Activesupport Concern,在一个问题中,我运行以下代码: self.user&.favorite(self, scope: [:watching]) if self.respond_to? user self.team&.user.favorite(self, scope: [:watching]) if self.respond_to? team 我在用户和团队中考虑了这个问题。 每次创建用户,我都会遇到以下错误: NameError:未定义的局部变量或方法“user”# 创建一个团队也是如此 为什么
self.user&.favorite(self, scope: [:watching]) if self.respond_to? user
self.team&.user.favorite(self, scope: [:watching]) if self.respond_to? team
我在用户
和团队
中考虑了这个问题。
每次创建用户
,我都会遇到以下错误:
NameError:未定义的局部变量或方法“user”#
创建一个团队
也是如此
为什么会发生这种情况?显然,User
没有响应实例上用户的方法(或等效方法)。但这就是为什么我添加了if self.response\u to?用户将
添加到语句中。您的问题是接收符号作为参数
self.user&.favorite(self, scope: [:watching]) if self.respond_to? :user
self.team&.user.favorite(self, scope: [:watching]) if self.respond_to? :team
这就是为什么如果未定义用户
或团队
方法,您将收到错误