Cameron Bass Cameron Bass - 6 months ago 10
Ruby Question

Method to render how many days remain in membership - Ruby on Rails

Currently I have method called

expiration_date
that calls the created_at and adds 1 year to that date. I now would like to make a method that says essentially how many days are left until it is
expiration_date
and call that on the view. I'll show my Model code for clarity and hopefully this will make more sense.

MODEL

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).strftime("%-m/%-d/%-y")
end

def days_till_expired
#code
end


end

CONTROLLER

class SubscribersController < ApplicationController
def index
@subscriber = Subscriber.all
end

def new
@subscriber = Subscriber.new
end

def create
@subscriber = Subscriber.create(subscriber_params)
if @subscriber.save
flash[:notice] = "Subscriber Has Been Successfully Created"
redirect_to new_subscriber_path(:subscriber)
else
render "new"
end
end

def search
@subscriber = Subscriber.new
end

def visit
@subscriber = Subscriber.find_by_phone_number(params[:phone_number])
if @subscriber
@subscriber.visit =+ 1
@subscriber.save
redirect_to subscribers_search_path(:subscriber)
else
render "search"
end
end


I have a view form where a user will type in their phone_number and it will flash a notice to aware them how much time they have left. I think that I will need to grab the user params of their phone number when it's sent in. does this make sense?

Answer

How about this

def days_till_expiration
  ((created_at + 1.year) - DateTime.now).to_i / 1.day
end
Comments