如何使用 where user_id =current_user.id 编写查找子句

How to write find clause using where user_id =current_user.id

我在 1 个用户和多个挑战之间建立了一对多的关系。我正在使用 rails 4 和 Devise

我想列出当前用户面临的挑战。

到目前为止我有

@challenge = User.find(current_user.id).challenges

我也试过了

@challenge = User.find(current_user).challenges

我也试过了@challenge = current_user.challenges

但它不起作用。我收到 "undefined methodeach' for nil:NilClass"` 的错误,这通常意味着 @challenge 没有被传递到视图 我犯了某种语法错误吗?

如果我在 rails 控制台中执行 User.find(1).challenges 它工作正常,所以大概我没有正确使用 current_user.id

当您尝试访问页面时,用户似乎未登录,因此 current_user 设置为 nil

current_user.challenges 将完成获取与此用户关联的所有 challenges 的工作。您可以在调用此代码之前使用 devise 中的 user_signed_in? 方法,以确保 current_user 始终可用。