Default value for date_helper in formtastic

拈花ヽ惹草 提交于 2019-12-14 01:05:25

问题


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.


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/1715582/default-value-for-date-helper-in-formtastic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!