【问题标题】:Undefined ruby object in javascriptjavascript中未定义的ruby对象
【发布时间】:2013-05-31 17:39:19
【问题描述】:

我只在变量确实存在时才尝试做某事(变量的名称是@filter),问题是我似乎无法弄清楚如何让代码工作。我不断得到

undefined method `male_filter' for nil:NilClass

即使第一个 if 应该可以解决问题。 这是javascript的实际代码:

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

我还尝试在名为 filterExists 的控制器中添加一个布尔值,并执行以下操作:

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

但我还是遇到了同样的错误:

undefined method `male_filter' for nil:NilClass

【问题讨论】:

  • 查看你生成的页面源代码!我不认为你的服务器端代码像你想象的那样工作。查看服务器端代码不会有帮助。

标签: javascript jquery ruby-on-rails ruby null


【解决方案1】:

问题是所有 ERB 都在服务器上进行解释,然后将 JavaScript 提供给运行它的客户端,您正在尝试混合服务器端和客户端逻辑。

只要您了解 ERB 是首先被解释的,那么您就可以像这样构建您的代码:

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

或者更简洁:

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

【讨论】:

  • 感谢您的解释,非常感谢。
【解决方案2】:

我认为这是一个 js.erb。您也可以在其中使用常规 Ruby:

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

等等

【讨论】:

  • 对不起,我忘了提,这是一个视图 -> html.erb。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-20
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多