在我执行的Rails控制台中
u = User.where(id: 1)
"he find the user with id = 1, but then"
u.email
我收到此错误:
NoMethodError: undefined method `email' for #<User::ActiveRecord
为什么rails console总是在寻找方法而不是属性? 如何查看特定属性?
我这样做是因为我在应用程序中有一个方法可以通过user_id找到一个协调器,就像这样
user_id = current_user.id
coordinator = Coordinator.where(user_id: user_id)
course_id = coordinator.course_id
答案 0 :(得分:4)
where
返回一个ActiveRecord::Relation
对象,这是一个数组。 email
仅存在于单个对象上。请尝试使用User.find()
。否则,请尝试User.where().first
以获取单个对象。
编辑:
正如评论者指出的那样,在这种特殊情况下,您可能更愿意使用find_by()
方法而不是where
。