【问题标题】:Helper method called upon in model file, not working模型文件中调用的辅助方法,不起作用
【发布时间】:2015-07-07 11:24:44
【问题描述】:

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

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 中的一个方法,定义了当前登录的用户。我在许多控制器方法中成功地使用了这种方法。但是,对于上面的用例,我收到错误消息undefined local variable or method 'current_user' for #<Invitation:0x007f699086bf40>

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller


    【解决方案1】:

    current_user 在模型层中不可用(它是 MVCCV 层上的助手和模型对 current_user 助手一无所知)。从你的助手传递user_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
    

    【讨论】:

      【解决方案2】:

      您必须将以下行添加到您的 ApplicationController:

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

      现在您应该可以使用控制器/模型中的方法了。

      【讨论】:

      • 不幸的是,事实并非如此。我的应用程序控制器中已经有了这个,并且辅助方法正在控制器中工作。只是不在模型中。我还想知道在我需要它的这个场合是否安全,立即让所有模型访问所有辅助方法。
      • 在控制器中包含一个助手类并让模型可以访问此类中的助手。
      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2011-07-28
      • 2013-07-27
      • 1970-01-01
      • 2011-05-27
      • 2017-05-01
      • 1970-01-01
      相关资源
      最近更新 更多