Jack
Jack

Reputation: 237

how to fill the default value of the "input" tag dynamically

In my vote system, i have the input tag of the "expire_at".and what i want to do is that fill the input tag dynamically with the date.the date is 7days later.

For example ,if i do nothing with "expire_at".it should be 2011-10-23 as default.(2011-10-16 with 7days later),how to?

Upvotes: 0

Views: 197

Answers (2)

sled
sled

Reputation: 14625

If +7 days is a default setting that applies everywhere, put it in your model:

In your model:

class MyModel < ActiveRecord::Base

  def expires_at
    # I'm not sure if this works, if not
    # wrap it in a if-clause like:
    # read_attribute(:expires_at).present? ? read_attribute(:expires_at) : 7.days.from_now

    read_attribute(:expires_at) || 7.days.from_now
  end
end

In your view:

<%= f.text_field :expires_at, @vote.expires_at.strftime('%Y-%m-%d') %>

If it is only for one specific form, do it like in bricker's answer: (without modifying your model of course)

In your view:

<%= f.text_field :expires_at, :value => (@vote.expires_at.present? ? @vote.expires_at : 7.days.from_now).strftime('%Y-%m-%d') %>

Upvotes: 1

bricker
bricker

Reputation: 8941

<%= f.text_field :expires_at, :value => @vote.new_record? ? Time.zone.now + 7.days : @vote.expires_at %>

Upvotes: 1

Related Questions