2

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.

lucasarruda
  • 1,462
  • 1
  • 25
  • 45
Bitwise
  • 8,021
  • 22
  • 70
  • 161

3 Answers3

4

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"
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
0

I feel like you're actually asking the wrong question here. Rather than doing this feature in Rails, you're asking a Ruby question which is "how do I work with interaction between Ruby datetime objects." I suggest you take at Ruby/Rails datetime objects and see how they work first.

That said, I'm pretty sure someone else is gonna post the answer you want to see.

dtc
  • 1,774
  • 2
  • 21
  • 44
  • @CameronBass np, have fun with ruby/rails! im stuck in java (lava) land for now :( – dtc Apr 26 '16 at 21:31
0

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.

Community
  • 1
  • 1
tadman
  • 208,517
  • 23
  • 234
  • 262