助手 - 未定义的方法`gsub'为零:NilClass

时间:2015-09-06 18:32:50

标签: ruby-on-rails ruby

我有这个功能

application_helper.rb

  User.group("users.category").
      select("users.id as user_id", "users.category", "MAX(users.created_at) as created_at", "users.notes")

查看

<!DOCTYPE html>
<html>
<head>
<style>
        .cgreen{ background-color: springgreen;}
        .cred{ background-color: red;}
        .cyellow{ background-color: yellow;}
        .ishidden{display:none;}
</style>
</head>
<body>

        <span>Service Date (MM/dd/yyyy)</span>&nbsp;
        <input class="service-date ishidden" value="09/23/2015 14:30:00" type="text"/>
        <button id="refresh">Refresh</button>
        <br/>
        <span>Indicator</span>&nbsp;
        <div id="indicator" style="height: 50px; width: 50px; display: inline-block;"></div>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script> 
<script>

    $(document).ready(function() {

        var colorCalculus = function(){

        var color = 'cred';
        var today = new Date();
        var serviceDate = new Date($('.service-date').attr('value'));

        var fifteenBackwards = new Date(serviceDate.getFullYear(), serviceDate.getMonth(), serviceDate.getDate() - 15);

        if(today < fifteenBackwards){
            color = 'cgreen';
            }
        else if(fifteenBackwards <= today && today <= serviceDate){
            color = 'cyellow';
            }

        $('#indicator').removeClass('cred cgreen cyellow');
        $('#indicator').addClass(color);
    };

        $('#refresh').click(function(){colorCalculus();});

        colorCalculus();

    });
</script>       
</body>
</html>

错误:

  

未定义的方法`gsub&#39;为零:NilClass

有时内容可以是def nl2br(s) s.gsub(/\n/, '<br/>') end ,这是处理它的最佳方法吗?

当我在函数中添加<%= nl2br(@event.rules).html_safe %> 时,我得到nil

1 个答案:

答案 0 :(得分:4)

简单的技巧,只需使用OR来设置默认值:

_GNU_SOURCE

此外,由于def nl2br(s) (s||'').gsub(/\n/, '<br/>') end 计算为空字符串,您可以执行以下操作:

nil.to_s