Rails - 我可以在控制台中访问对象,但不能在应用程序中访问

时间:2013-12-11 19:58:19

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord

UserNotification belongs_to用户和用户has_many UserNotification。

我正在尝试通过用户访问通知。如果我在控制台中运行:

User.find(31).user_notifications

返回以下用户:

<Employer id: 31, email: "person1@commercial.com", ...>

上面的代码是正确的(用户可以是“雇主”或“自由职业者”类型。我相信这称为多态)。但是,如果我跑:

User.where(email: 'person1@commercial.com').user_notifications

我被告知:

undefined method `user_notifications'

这应该给我与上面使用的'find'方法相同的用户。在我的应用程序中,我在使用current_user时遇到与user_notification相同的问题。例如,我有:

@notifications = current_user.user_notifications.inspect

我以与我在控制台用户31中使用的用户身份登录时执行此操作。但是,user_notifications显示为nil。

如何通过current_user访问user_notification?

1 个答案:

答案 0 :(得分:1)

.where返回一个数组。所以当你使用它时,你需要指定你想要的结果:

User.where(email: 'person1@commercial.com').first.user_notifications

有关详细说明,请参阅此问题:Rails .where vs .find