User7777
User7777

Reputation: 299

undefined method `-' for nil:NilClass in ruby model

I have defined a method inside my model class in ruby as below. But when I try using that method I am getting undefined method `-' for nil:NilClass. I am not able to figure out where I am going.

bus.rb

def seat_avaliable
    (self.seat - self.students.count)
end

Upvotes: 2

Views: 1512

Answers (1)

lacostenycoder
lacostenycoder

Reputation: 11226

You can't call or chain methods on a nil object. You're trying to subtract something from nil which the error has told you. So you can fix this with:

def seat_avaliable
  if seat.is_a?(Integer) && students&.any?
    seat - students.count > 0
  end
end

Change your view code to this

<% if bus.seat_available %><td>Seat Available</td><% end %>

Upvotes: 2

Related Questions