Ruby on rails 在模型文件中调用了Helper方法,不起作用

Ruby on rails 在模型文件中调用了Helper方法,不起作用,ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller,Ruby On Rails,Ruby,Ruby On Rails 4,Model View Controller,在控制器中的创建方法中,我有: if logged_in_admin? @invitation.set_ids 在邀请模型中: def set_ids self.person_one_id = current_user.id end current_user是app/helpers/sessions_helper.rb中的一个方法,用于定义当前登录的用户。我在许多控制器方法中成功地使用了这种方法。然而,对于上面的用例,我得到了错误消息未定义的局部变量或方法“current\u use

在控制器中的创建方法中,我有:

if logged_in_admin?
  @invitation.set_ids
在邀请模型中:

def set_ids
  self.person_one_id = current_user.id
end
current_user
是app/helpers/sessions_helper.rb中的一个方法,用于定义当前登录的用户。我在许多控制器方法中成功地使用了这种方法。然而,对于上面的用例,我得到了错误消息
未定义的局部变量或方法“current\u user”,用于#


为什么我会收到此错误消息?这是因为这次我在模型文件中使用了helper方法,这是不允许的吗?如果不允许这样做,那么安全地将
@invitation
个人id
设置为等于当前登录用户id的最佳方法是什么?

您必须在应用程序控制器中添加以下行:

class ApplicationController < ActionController::Base
    protect_from_forgery with: :exception
    include SessionsHelper
end
class ApplicationController

现在,您应该能够使用控制器/模型内部的方法。

当前用户
在模型层中不可用(它是
MVC
,您在
CV
层和模型上的助手对
当前用户
助手一无所知)。将助手的
user\u id
作为参数传递:

some_helper.rb

def my_helper
  if logged_in_admin?
    @invitation.set_ids(current_user.id)
# .....
model.rb

def set_ids(user_id)
  self.person_one_id = user_id
end

不幸的是,事实并非如此。我已经在我的应用程序控制器中有了它,并且助手方法正在控制器中工作。只是模型中没有。我还想知道,在我需要它的情况下,它是否安全,即立即向所有模型授予对所有helper方法的访问权限。在控制器中包含helper类并不会向模型授予对此类中的helper的访问权限。