【问题标题】:Ruby on rails - Helper method - undefined method `log_in' in Ruby on railsRuby on rails - 辅助方法 - Ruby on rails 中未定义的方法“log_in”
【发布时间】:2014-12-04 00:27:49
【问题描述】:

我正在根据 Michael Hartl 的 Ruby on Rails Tutorial 3rd Edition 实现登录。卡在第 8 章。

SessionsHelper 中定义一个新的log_in 辅助函数,如下所示。当我尝试访问SessionController 中的相同函数时,我得到了未定义的方法log_in

module SessionsHelper

  def log_in(user)
    session[:user_id] = user.id
  end
end

和SessionCONtroller代码是

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      log_in user
      redirect_to user
    else
      flash[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您缺少ApplicationController 部分here,它在控制器中包含帮助程序,因此可以直接访问其方法:

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

    【讨论】:

    • 谢谢!你拯救了我的一天!
    • 酷,很高兴能提供帮助。是否愿意将我的答案设置为正确的答案,以便从“未回答”的存储桶中删除?
    猜你喜欢
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2013-08-14
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多