undefined method `length' for nil:NilClass
11,998
It is because you have default value nil
for content
column. So you can't call length
on nil
. If you want to use length
on content
you need to set default
value as empty string("")
or you can use to_s
first and then length
<%= 350 - @status.content.to_s.length %>
or
<%= 350 - (@status.content.try(:length) || 0) %>
Author by
Jaqx
Updated on June 04, 2022Comments
-
Jaqx almost 2 years
When I create a new user and view the user's profile Im getting the following error I think because the user has not created a status yet:
undefined method `length' for nil:NilClass
It's coming from 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 %>
User Controller:
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
-
Jaqx about 11 yearsIt is. I'm saying I havn't created a status yet thus I get an error from that line. What should i do?
-
Kyle d'Oliveira about 11 yearsYou could either default content in the DB to be zero, or you do something like
@status.content.try(:length)||0
-
Jaqx about 11 yearsI think that did the trick but im going to check again. Does the to_s set it to an empty string automatically?