Reputation: 11
Table years
includes following fields: id
, name
.
Table course
includes: id
,
table year_courses
includes: year_id
and course_id
.
I receive an exception:
undefined method `name' for nil:NilClass and undefined method `id' for nil:NilClass
Upvotes: 0
Views: 270
Reputation: 2946
This is happening because for some of your YearCourse (yc) objects, they do not have years, and some do not have courses so when rails tries to invoke .name
on an already nil value yc.year
you end up with a 'nilnil class' error. The other error you have is exactly the same except its for course.
To solve this in particular, you could try the following:
<%= content_tag_for :tr, @year_courses do |yc| %>
<%= yc.year.try(:name) %></div>
<%= yc.course.try(:id) %></div>
<% end %>
.try will "try" to invoke the method, and if it fails it will not raise an error. That being said, generally in rails coding, overuse of the method try
can lead to a lot of bad coding practice. It can also indicate a code smell that would point to the fact that its possible the modelling could be done in a better way. Otherwise, you can always check if yc.year.present?
and yc.course.present?
before you try invoking .name
and .id
respectively.
Upvotes: 2
Reputation: 2508
Another alternative to solve the nil:NilClass error is to dump the data(that's if your app is using dummy data that you are experimenting with), reseed the data with all necessary attributes. rake db:reset
. or rake db:drop
and then rake db:seed
Upvotes: 0