如何在application_controller中修复未定义的方法错误?

时间:2015-03-01 17:12:13

标签: ruby-on-rails ruby

当用户未登录或者目标中没有任何内容时,我们需要在应用程序控制器中放置什么才能使set_top_3_goals方法正常工作?

因为我收到了这个错误:

NoMethodError (undefined method `goals' for nil:NilClass):
  app/controllers/application_controller.rb:7:in `set_top_3_goals'

我的控制器代码:

class ApplicationController < ActionController::Base
  before_action :set_top_3_goals
  protect_from_forgery with: :exception
  include SessionsHelper

  def set_top_3_goals
    @top_3_goals = current_user.goals.unaccomplished.top_3
  end

  private

    # Confirms a logged-in user.
    def logged_in_user
      unless logged_in?
        store_location
        flash[:danger] = "Please log in."
        redirect_to login_url
      end
    end
end

1 个答案:

答案 0 :(得分:1)

我在您的控制器上添加了一个带有logged_in_user方法的before_action,然后再调用另一个before_action

class ApplicationController < ActionController::Base
  before_action :logged_in_user
  before_action :set_top_3_goals
end

请注意,声明顺序在此处很重要。