访问不同状态下的用户对象(Ruby on Rails、RESTful 身份验证)

发布于 2024-07-17 07:47:13 字数 437 浏览 6 评论 0原文

在我的 Rails 应用程序中,我有一个用户模型(或多或少由 RESTful 身份验证构建),以及属于该用户的其他几个模型。 举例来说:

user has_many :posts

post own_to :user

在用户资源中的任何位置,我都可以按预期访问用户变量。 @user.name、@user.email、@user.login 等都返回预期的对象。

但是,我似乎无法从任何其他资源(在本例中为帖子)访问任何这些属性,而不返回 nil(nil 而不是 NoMethodError)。

为什么是这样? 对我来说更奇怪的是,我可以很好地调用 current_user,如 current_user.namecurrent_user.email,但不能调用用户有问题。

In my Rails application I have a User model (more or less built by RESTful Authentication), and several other models belonging to the user.
So let's say, for example:

user has_many :posts

post belongs_to :user

Anywhere in the users resource I can access the user variables as I would expect.
@user.name, @user.email, @user.login, etc. all return the expected object.

However, I can't seem to access any of these attributes from any other resource (in this example, posts) without it returning nil (nil rather than a NoMethodError).

Why is this? It seems even stranger to me that I can call current_user just fine, as in current_user.name, current_user.email, but not for the user in question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

说谎友 2024-07-24 07:47:13

您可以在这里谈论两个用户。
1) 当前登录的用户
2)该帖子所属的用户

应该能够通过current_user访问到当前登录的用户。
帖子所属的用户需要在帖子控制器中设置:

@user = Users.find(@post.user_id)

@user = @post.user

There are two users you could be talking about here.
1) the currently logged in user
2) the user who the post belongs to

the currently logged in user should be able to be accessed through the current_user.
the user who the post belongs to will need to be set in the Posts controller:

@user = Users.find(@post.user_id)

or

@user = @post.user
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文