views:

811

answers:

3

As basic as it sounds, I can't make the date_helper default to a date, as in:

- semantic_form_for resource do |f|
  - f.inputs do
    = f.input :issued_on, :default => Date.today
  = f.buttons

The above just renders blank columns if resource does not have a date.

Would appreciate any pointer on what I'm possibly doing wrong.

+2  A: 

You can set the default on the object itself on your controller

def edit
  @resource = Resource.find(params[:id])
  @resource.issued_on ||= Date.today
end
hgimenez
+1, beat me by a couple minutes. I think this way is the best practice.
mculp
moving defaults to the controller, gracias.
hakanensari
+1  A: 

You should define after_initialize in the model. If an after_initialize method is defined in your model it gets called as a callback to new, create, find and any other methods that generate instances of your model.

Ideally you'd want to define it like this:

class resource < ActiveRecord::Base

  def after_initialize
    @issued_on ||= Date.today
  end
  ...
end

Then your view would look like this:

- semantic_form_for resource do |f|
  - f.inputs do
    = f.input :issued_on
  = f.buttons

This will also guard against nil errors if you find a record that doesn't have those fields set. However, that shouldn't happen unless you create a record directly without ActiveRecord.

EmFi
A: 

We've recently implemented a :selected option against all :select, :radio and :check_boxes inputs in Formtastic, so it'll be in the next patch release (0.9.5) or 1.0. Until then, the advice to create an after_initialize or to set the default in the controller is good advice, however I do think that sometimes the best person to decide on the default value is the designer, who may not be comfortable the controllers or models, which is why we added this as part of the Formtastic DSL.

Justin French