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