Hakan Ensari
Hakan Ensari

Reputation: 1979

Default value for date_helper in formtastic

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.

Upvotes: 4

Views: 4289

Answers (5)

TerryS
TerryS

Reputation: 7609

I like the following way

after_initialize :set_issued_on

def set_issued_on
  @issued_on||=Date.today
end

Bit longer, but nice and clear

Upvotes: 0

ForceMH
ForceMH

Reputation: 9

you can put following in your model file

def after_initialize
    self.start ||= Date.today
    self.token ||= SecureRandom.hex(4)
    self.active ||= true
end

the above issued

@issued_on ||= Date.today

has not worked for me

Upvotes: 0

Justin French
Justin French

Reputation: 2875

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.

Upvotes: 2

EmFi
EmFi

Reputation: 23450

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.

Upvotes: 2

hgmnz
hgmnz

Reputation: 13306

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

Upvotes: 7

Related Questions