Using datetime_select together with a virtual field
- October 28th, 2008
- Write comment
I came across this problem just today, it cost me about 30 minutes to 1 hour just figuring out what I did wrong not to mention the time I spent trying to look for the solution. Luckily I stumbled upon this ticket. here Apparently this problem has already been reported and a patch has already been submitted over a year ago. But it hasn’t been pushed to rails core yet. Anyways to summarize the situation, heres how one can stumble into this problem:
Lets say you have a view which uses the date helper datetime_select like so:
<% form_for(:ticket, :url => tickets_path) do |f| %> <%= f.text_field :title -%> <%= f.text_field :description -%> <%= f.datetime_select :date_this_ticket_might_get_resolved -%> <% end %>
And here’s a sample controller:
class TicketsController < ApplicationController def create @ticket = Ticket.new(params[:ticket]) @ticket.save end end
And lastly the model:
class Ticket < ActiveRecord::Base
def date_this_ticket_might_get_resolved=(val)
self.date_of_submission = Time.mktime( val[:year], val[:month], val[:day],
val[:hour], val[:minute]) + 1.year
end
def date_this_ticket_might_get_resolved
self.date_of_submission + 1.year # add another year just to be sure
end
end
You will get something like this error:
NoMethodError (You have a nil object when you didn't expect it!The error occurred while evaluating nil.klass): /vendor/rails/activerecord/lib/active_record/base.rb:2645:in `execute_callstack_for_multiparameter_attributes' /vendor/rails/activerecord/lib/active_record/base.rb:2644:in `each' /vendor/rails/activerecord/lib/active_record/base.rb:2644:in `execute_callstack_for_multiparameter_attributes' /vendor/rails/activerecord/lib/active_record/base.rb:2630:in `assign_multiparameter_attributes' /vendor/rails/activerecord/lib/active_record/base.rb:2375:in `attributes='
I was using Rails 2.1 with Ruby 1.8.6 , The patch can be found on this link, Just follow the instructions its just a one liner change on ActiveRecord::Base.