Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Created_at.1.year.from_now - Rails

I need to make a method that renders a date to a table that is one year past the creation date. I've tried the line as listed in the title, but that didn't work. I have a table right now that lists "date joined" next to it I'd like it to say "date expired". which will be one year from the date joined.

Example:

class Subscriber < ActiveRecord::Base
  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :email, presence: true
  validates :phone_number, presence: true

  def date_joined
   created_at.strftime("%-m/%-d/%-y")
  end

  def expiration_date
   created_at.1.year.from_now
  end
end

How should I format that expiration_date method. The date_joined works fine.

like image 251
Bitwise Avatar asked Oct 26 '25 06:10

Bitwise


2 Answers

You should add 1.year to the created_at time object:

def expiration_date
  created_at + 1.year
end

Formatted:

def expiration_date
  (created_at + 1.year).strftime("%-m/%-d/%-y")
end

rails console:

=> some_object.created_at
=> Wed, 12 Apr 2016 17:37:12 UTC +00:00
=> some_object.created_at + 1.year
=> Wed, 12 Apr 2017 17:37:12 UTC +00:00
=> (some_object.created_at + 1.year).strftime("%-m/%-d/%-y")
=> "4/12/17"
like image 150
Philidor Avatar answered Oct 28 '25 21:10

Philidor


Remember that created_at isn't populated until the model is saved, your calculations won't work until then. This could be a problem.

The date_joined method you have shouldn't exist. Any formatting concerns should be the responsibility of your view, so push that logic in there like this:

 <%= model.created_at.strftime("%-m/%-d/%-y") %>

You can even define a format for your dates using the locales as demonstrated in this question where you can add this to config/locales/en.yml:

en:
  date:
    formats:
      default: "%-m/%-d/%-y"
  time:
    formats:
      default: "%-m/%-d/%-y %H:%M"

Then you can use this in your view as the default without any special handling required:

<%= model.created_at %>

That will format all times the way you want instead of you having to go out of your way to define special formatter methods for each model and then remember to call them.

When it comes to computing dates in the future you can do math on dates:

def expiration_date
  (self.created_at || DateTime.now) + 1.year
end

That will work even if the model hasn't been saved.

like image 34
tadman Avatar answered Oct 28 '25 19:10

tadman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!