I have a Rails 3.2.8 application with a model called Task. In my Task model I have a datetime property called ‘complete_date’. When I try to view my complete_date in a view with..
<%= @task.complete_date.strftime('%b %e, %Y') %>
I get an error saying “undefined method `strftime’ for nil:NilClass”. However, the complete_date field is not null. The following query..
mysql> select count(*) from tasks where complete_date is null;
returns 0 rows. I can retrieve the complete_date, in the same view, with the following code…
<% @task.attributes.each_pair do |name, value| %>
<% if name == "complete_date" %>
<%= value.strftime('%b %e, %Y') %>
<% end %>
<% end %>
This works perfectly, so it seems the problem is only with accessing the attribute with the dot notation (@task.complete_date). I have listed ‘complete_date’ as an attr_accessible and an attr_accessor in my Task model. Any idea why I am always getting nil when referencing the complete_date field with @task.complete_date? Thanks.
You should remove
attr_accessor :complete_date. Becauseattr_accessorcreates two methods (#complete_date&#complete_date=) and uses the instance variable@complete_date, that is nil, because its not filled with the value of the record’s attribute. These two methods overrided ActiveRecord attribute accessor methods.