Waclock
Waclock

Reputation: 1716

Undefined ruby object in javascript

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

Upvotes: 0

Views: 119

Answers (2)

Alex Peachey
Alex Peachey

Reputation: 4676

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 %>
});

Upvotes: 2

MrDanA
MrDanA

Reputation: 11647

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.

Upvotes: 1

Related Questions