【发布时间】:2015-06-25 04:15:42
【问题描述】:
我正在尝试确保以下方法
def current_user
current_user = current_member
end
适用于我所有控制器中的所有操作 我试过把它放在 ApplicationsController 中,但没有成功。
我尝试使用以下解决方案
Where to put Ruby helper methods for Rails controllers?
没有效果。
Rails 方式的解决方案是什么?
我的 ApplicationsHelper 中有相同的方法,我可以在我的视图中访问它没问题。
编辑:
提供更多细节。 我有一个从头开始构建的带有身份验证系统的应用程序,它使用了一个名为“current_user”的 SessionHelper 文件中的函数
我一直在我的应用程序中实现设计,并维护我的用户模型来保存用户详细信息,但创建了一个成员模型来保存设计身份验证信息(即,将用户个人资料信息与设计所建议的使用表分开由文档)。
这给了我一个名为 current_member 的设计辅助方法(基于我对模型的命名)。
我的应用程序中到处都有“current_user”,无论是在控制器操作中还是在视图中。
我想创建一个应用程序范围的助手,它将 current_member 别名为 current_user。严格来说,在我的问题中,我的功能是错误的 - 这会将 current_user 分配给成员类的实例。由于成员和用户之间存在一对一的关系,外键为 member.id 正确的功能是....
定义当前用户 如果成员签名? current_user = User.find_by_member_id(current_member.id) 结尾 结束
我的应用程序助手:
module ApplicationHelper
def current_user
if member_signed_in?
current_user = User.find_by_member_id(current_member.id)
end
end
end
这会处理所有视图中的 current_user, 但我无法让它在控制器中工作......例如,在我的 UserController 的“显示”操作中查看此代码
def show
@associates = []
@colleagues = current_user.nearbys(1000).take(20)
@colleagues.each do |associate|
unless current_user.following?(associate) || current_user == associate
@associates.push(associate)
end
end
impressionist(@user)
end
忘记逻辑-我只是使用地理编码器来查找几乎用户。它的 current_user 正在解析为“nil”。
即使我放了
before_action :current_user
def current_user
if member_signed_in?
current_user = User.find_by_member_id(current_member.id)
end
end
在 UserController 中,current_user 不在操作中工作。我在其他控制器的操作中也有 current_user 并且应用程序在这些点上中断,但当 current_user 在视图中时不会。
如果您需要更多信息,请告诉我。
编辑 2:
我加了
before_action :authenticate_member!
到 UsersController,但这仍然没有效果。
编辑 3:
我是个白痴。发生 nil 类错误是因为我在数据库中没有种子数据,因此
@colleagues = current_user.nearbys(1000).take(20)
@colleagues 为 nil,因此在 nil 上调用“take”会引发错误。 菜鸟失误。
【问题讨论】:
标签: ruby-on-rails-4 methods controller