0

I'm trying to do something ONLY if a variable DOES exist (the variable's name is @filter), the problem is I can't seem to figure out how to get the code to work. I keep getting

undefined method `male_filter' for nil:NilClass

even when the first if should do the trick. Here's the actual code of the javascript:

$(document).ready(function(){
    if(typeof <%=@filter%>!='undefined'){
        if(typeof <%[email protected]_filter%>!='undefined'){
            if(<%[email protected]_filter%>=='18'){
                $('#18M').addClass('active');
            }
            else if(<%[email protected]_filter%>=='21'){
                $('#21M').addClass('active');
            }
            else if(<%[email protected]_filter%>=='24'){
                $('#24M').addClass('active');
            }
        }
    }
}

I also tried adding a boolean in the controller called filterExists, and did the following:

    var filterExists=<%=@filterExists%>;
    if(filterExists==true){...}

But I still got the same error:

undefined method `male_filter' for nil:NilClass
1
  • View your page source that is generated! I do not think your serverside code is working like you think it is. Looking at the serverside code is not going to help. Commented May 31, 2013 at 17:43

2 Answers 2

2

The problem is all of the ERB is interpreted on the server and then the JavaScript is served to the client where it is run, you are trying to mix server-side and client-side logic.

As long as you understand the ERB is interpreted first, then you can structure your code like this:

$(document).ready(function(){
  <% if @filter.present? %>
    <% if @filter.male_filter == '18' %>
      $('#18M').addClass('active');
    <% end %>
    <% if @filter.male_filter == '21' %>
      $('#21M').addClass('active');
    <% end %>
    <% if @filter.male_filter == '24' %>
      $('#24M').addClass('active');
    <% end %>
  <% end %>
});

Or more concisely:

$(document).ready(function(){
  <% if @filter %>
    $('#<%= @filter.male_filter %>M').addClass('active');
  <% end %>
});
Sign up to request clarification or add additional context in comments.

Comments

1

I assume this is a js.erb. You can use regular Ruby in those as well:

<% if @filter.present? %>
  <% if @filter.male_filter == "18" %>
    $('#18').addClass('active');
  <% end>
<% end %>

Etc.

1 Comment

I'm sorry I forgot to mention, this is a view -> html.erb.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.