2

当我创建一个新用户并查看用户的个人资料时,我收到以下错误,我认为是因为用户尚未创建状态:

undefined method `length' for nil:NilClass

它来自 Status_form:

<%= form_for [@status], :url => user_status_path(current_user) do |f| %>
  <div class="field">
    <%= f.text_area :content, id:"status_box", maxlength:350, placeholder: "Say something." %>
  </div>
  <%= f.submit "Update", id:"status_btn", class: "btn btn-small btn-primary" %>

  <span id="counter">Characters left: <%= 350 - @status.content.length %></span> #this is the source of the error

  <script type="text/javascript">
    $('#status_box').keyup(function () {
        var left = 350 - $(this).val().length;
        if (left < 0) {
            left = 0;
        }
        $('#counter').text('Characters left: ' + left);
    });
  </script>
<% end %>

用户控制器:

def new
  @user = User.new
end

def create
  @user = User.new(params[:user])
  if @user.save
    sign_in @user
    redirect_to root_path
  else
    render 'new'
  end
end

def show
  @user = User.find(params[:id])
  @status = @user.status || @user.build_status
end
4

2 回答 2

3

这是因为您有列的默认值nilcontent所以你不能打电话lengthnil如果你想使用lengthoncontent你需要设置defaultvalue asempty string("")或者你可以to_s先使用然后length

   <%= 350 - @status.content.to_s.length %>

或者

   <%= 350 - (@status.content.try(:length) || 0) %>
于 2013-02-19T18:16:25.377 回答
0

你的控制器中有这个:

  @status = @user.status || @user.build_status

看起来错误来自

@status.content.length

我敢打赌@status 的“内容”是零。

于 2013-02-19T18:12:09.130 回答