Topic: Chronic Datetime Parsing and Update action

Hey, I am trying to get Chronic gem to work parsing dates(datetime) from a textfield. It works perfectly well creating new records, but doesn't seem to work at all (inserting null) for the update action. Here is my controller. I am pretty sure the problem has to do with the phrasing in my update action.

Thanks in advance everybody:

  def new
    @note = Note.new
  end

  def create
    @note = Note.new(params[:note])
    @note.event_start = Chronic.parse(params[:note][:event_start])
    if @note.save
      flash[:notice] = 'Note was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @note = Note.find(params[:id])
  end

  def update
    @note = Note.find(params[:id])
    @note.event_start = Chronic.parse(params[:note][:event_start])
    if @note.update_attributes(params[:note])
      flash[:notice] = 'Note was successfully updated.'
      redirect_to :action => 'show', :id => @note
    else
      render :action => 'edit'
    end
  end

Last edited by iasa (2006-12-17 23:56:03)

Re: Chronic Datetime Parsing and Update action

The problem is that this line:
@note.event_start = Chronic.parse(params[:note][:event_start])
sets the @note.event_start value to what it should be.  But then this line:
@note.update_attributes(params[:note])
overwrites that value with the event_start value from the params - which is bogus apparently.

What you could do:
@note = Note.find(params[:id])
params[:note][:event_start] = Chronic.parse(params[:note][:event_start])
   if @note.update_attributes(params[:note])

Re: Chronic Datetime Parsing and Update action

Chronic is pretty rad. You could also use change .update_attributes to .save and use the same line from the create action. Not quite sure whether .update_attributes is preferred, though - somebody definitely correct me if I am giving bad advice here.

@note.event_start_at = Chronic.parse(params[:note][:event_start_at])  
if @note.save

If you did use .save for both the create and update actions you might want to consider moving the code to a :before_save in the Note model to keep the controller as minimal as possible. I am also not sure quite how you would phrase the :before_save call though.