Ruby on rails应用程序助手不在索引视图中工作

时间:2014-03-22 07:33:18

标签: ruby ruby-on-rails-4

我是铁轨上的红宝石的新手,我开始喜欢它了。我刚刚发现在我的视图中使用帮助器的问题。我无法在我的帮助器中看到我在索引视图中创建的链接,但我可以看到其他视图的链接。这有什么问题?请帮忙。非常感谢。这是我的代码

Application_helper.rb

module ApplicationHelper


def main_menu
    link_to("Go to Main Menu", {controller: 'access', action: 'index'})
end


end

index.html.erb(帮助者不在这里工作)

<% @page_title = "Admin users" %>
<%= main_menu() %>
<div class="admin_user index">
<h2>Admin Users</h2>
</div>

输出: enter image description here

edit.html.erb(帮助程序在这里工作)

<%= main_menu() %>
<div class="edit user">
<h1>Edit user form</h1>
 </div>

输出: enter image description here

1 个答案:

答案 0 :(得分:0)

此辅助方法将按controlleraction找到路径:

module ApplicationHelper
  # @note `return`s below are for illustration but not required
  # @see https://github.com/rails/journey
  def link(txt, ctl, act)
    begin
      x = Rails.application.routes.routes.select {|x| x.defaults[:controller] == ctl and x.defaults[:action] == act}.first.path.spec.left.to_s

      return link_to(txt.html_safe, x)
    rescue => e
      message = "ERROR route does not exist; controller: #{ctl}, action: #{act}; #{e.message}"

      # log
      Rails.logger.error(message)

      # raise (not graceful)
      raise message

      # or return (graceful)
      return nil
    end
  end

end


# in the view
link('dude&nbsp;awesome', 'controller_name', 'action_name')
#=> <a href="/controller/action_name">dude&nbsp;awesome</a>

使用上述方法,您可以像这样修改application_helper.rb

def main_menu
  link("Go to Main Menu", 'access', 'index')
end

该方法的Parens ()不是必需的...尝试这种语法,看看你是否喜欢它:

<%= main_menu %>