1

I have a field token_number in my database which i want to assign 1 more than the previous record.

for example in terms of array

 token_number[2] = token_number[1] + 1

And the value would be 1 for the first record. How can a assign a variable in the model which changes everytime i create a new record from my controller.

And my next condition is that the variable be reset to 0 every time when the current time i.e Time.now is the midnight. I tried it like this

class Ticket < ApplicationRecord
    before_create :update_token_number

private
    def update_token_number
        date = Time.now
         time_zone = Time.zone # any time zone really
         timeday = time_zone.local(date.year, date.month, date.day)
         midday = timeday.beginning_of_day
        if date == midday
            num = 0
            num = num + 1
        else
            num = num + 1
        end
            self.token_num = num
        #end
    end
end

if it runs also the value given to the field is always 1.

Please help

2 Answers 2

1

I suggest you to right a rake task using whenever gem to reset token_number to 0. Something like

every 1.day, :at => '12:00 am' do
  runner "Ticket.reset_token_number"
end

and use the before_create callback to update the value as you mentioned in the code snippet.

class Ticket < ApplicationRecord
  before_create :update_token_number

private
  def update_token_number
    self.token_num +=1
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

You need to change method to class method self.update_token_number
@promond thanks but could u please tell me in detail as i m not that well aware of rake task. Sorry to bother but if u could elaborate it then could be big help. If i m missing anything in information then please ask....
@Mannish If you go through the documentation of whenever gem, github.com/javan/whenever. You will get to know how to schedule tasks.
0

If I were you I would not manually create tokens like this. I think you should try Json Web Token Gem.

1 Comment

that would be great if i could do it with gem, I will try anyhow but want to learn this as well so that i can be confident in future while doing other stuffs relating to this issue, Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.