简体   繁体   中英

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. I created a helper method called nav "active", and I have a variable called 'link' in the view that increments up for each step. The idea is to have params[:id] == link , and make the class active when that is the case . However, being newer to rails and ruby I am not sure how to implement this. 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. 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 . Now link will be defined in the helper method.

<% 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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