简体   繁体   中英

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.

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

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM