简体   繁体   English

使用红宝石通过辅助方法使类活动-变量错误

[英]Using ruby to make a class active via helper method - error in variables

I have been having problems with my coffeescript, so instead I would like to use ruby to make my classes active in the view when clicked. 我的coffeescript一直存在问题,因此我想使用ruby在单击时使我的类在视图中处于活动状态。 I created a helper method called nav "active", and I have a variable called 'link' in the view that increments up for each step. 我创建了一个名为nav“ active”的助手方法,并且在视图中有一个名为“ link”的变量,该变量会为每个步骤递增。 The idea is to have params[:id] == link , and make the class active when that is the case . 这个想法是要有params [:id] == link,并在这种情况下使该类处于活动状态。 However, being newer to rails and ruby I am not sure how to implement this. 但是,对于Rails和ruby较新,我不确定如何实现这一点。 Any help would be appreciated. 任何帮助,将不胜感激。

My error 我的错误

 undefined local variable or method `link' for #<#<Class:0x007fb21e087820>:0x007fb21e53fd18>

My Method in application helper 应用程序助手中的“我的方法”

    def nav_active(options = {})

      return "active" if params[:id] == link

    end

My view 我的观点

     <% icon= ["icon-link", "icon-bar-chart", "icon-edit", "icon-beaker","icon-link", "icon-bar-chart", "icon-edit", "icon-beaker"] %>
    <% link = 0 %>

    <% @step_list.each_with_index do |step, i| %>

    <% case step.media_type %>
    <% when 'video' %>
     <% link += 1 %>
             <li class="<%= nav_active %>">
               <span class="glow"></span>
               <a href="<%= link %>">
                  <i class='icon-info-sign icon-2x'></i>
                  <span>Video</span>
               </a>
             </li>


<% when 'excel' %>
<% link += 1 %>
        <li class="<%= nav_active %>">
          <span class="glow"></span>
          <a href="<%= link %>">
              <i class="<%= icon[i] %> icon-2x"></i>
              <span>Step <%= i %> </span>
          </a>
        </li>

<% else %>
<% link += 1 %>
        <li class="dark-nav <%= nav_active %> ">
          <span class="glow"></span>
         <a href="<%= link %>">
              <i class="<%= icon[i] %> icon-2x"></i>
              <span>Step <%= i %></span>
          </a>
        </li>

<% end %>   

The helper method nav_active doesn't have access to the local variables in your view. 辅助方法nav_active无法访问视图中的局部变量。 You have to pass that in as an argument. 您必须将其作为参数传递。

# Helper
def nav_active(link)
  return "active" if params[:id] == link
end

This helper now accepts an argument named link . 现在,该帮助器接受名为link的参数。 Now link will be defined in the helper method. 现在, link将在helper方法中定义。

<% link += 1 %>
<li class="dark-nav <%= nav_active link %> ">

In the view you also must also pass in the current value of link, so the helper method can operate on it. 在视图中,您还必须传入链接的当前值,以便helper方法可以对其进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM