如何在application.controller.rb中使用自定义方法?

时间:2013-01-12 07:26:22

标签: ruby-on-rails ruby-on-rails-3

我是铁杆和红宝石的新手。我对rails~

中的一些约定感到困惑

我写了一个像这样的方法:

def show_session_counter?
  if session[:counter] && session[:counter] > 4
  end
end

...并希望在application.html.erb中使用这样的方法:

<% if show_session_counter? %>
      <li><a href="#"><%= pluralize session[:counter], "time" %></a></li>
<% end %>

首先,我尝试将该方法放在application.controller.rb中,因为我认为该方法将在application.html.erb中使用。我试着将它作为普通方法和私人方法。都没有工作。

然后我将该方法放在application_helper.rb中并​​且它可以工作。

所以我的问题是:为什么第一种方式不起作用?有没有&#34; rails约定&#34;这里吗?

非常感谢你!

1 个答案:

答案 0 :(得分:1)

当您将方法放入控制器并希望在视图中使用它时,您需要将其声明为helper_method

helper_method :show_session_counter?

def show_session_counter?
  if session[:counter] && session[:counter] > 4
  end
end