在 Rails 视图中访问应用程序控制器

3

我在应用程序控制器中有一个操作

def is_customer_logged_in?
    !!session[:customer_id]
  end

在我的看法中,我试图像这样访问application_controller动作

<% unless is_customer_logged_in? %>
    some functions
<% end %>

上面的代码是部分布局。
我遇到的是以下错误信息。
undefined method `is_customer_logged_in?' for #<#<Class:0xb51a5300>:0xb5616484>
2个回答

6
你可以定义它为一个帮助方法,并且你应该能够在视图中访问该方法。
# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

  def is_customer_logged_in?
    !!session[:customer_id]
  end

  helper_method :is_customer_logged_in?
end

必须将其定义为helper吗?为什么它在application_controller中不起作用,你能解释一下吗?我无法理解。 - Prabhakaran
3
@Setout,若要使控制器方法在视图中可用,需要将其声明为辅助方法(helper)。请参考此文档:http://www.rubydoc.info/docs/rails/AbstractController/Helpers/ClassMethods:helper_method - vee

0

尝试 helper_method: is_customer_logged_in?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接