Reputation: 23
I need the system to run the following code everyday but I don't know how to do accomplish this.
@user = User.all
date = Date.today
if date.workingday?
@user.each do |user|
if !Bank.where(:user_id => user.id , :created_at => (date.beginning_of_day..date.end_of_day) , :bank_type => 2 ).exists?
banco = Bank.new()
banco.user = user
banco.bank_type = 2
banco.hours = 8
banco.save
end
end
end
Upvotes: 0
Views: 58
Reputation: 211670
The most conventional way is to set this up to be executed with rails runner
in a cron
job.
There are tools like whenever
that make it easier to create these jobs by defining how often they need to be executed in Ruby rather than in the peculiar and sometimes difficult to understand crontab
format.
As a note, User.all
is a very dangerous thing to do. As the number of users in your system grows, loading them all into memory will eventually blow up your server. You should load them in groups of 100 or so to avoid overloading the memory.
Additionally, that where
clause shouldn't be necessary if you've set up proper has_many
and belongs_to
relationships here. I would expect this could work:
unless (user.bank)
user.create_bank(
bank_type: 2,
hours: 8
)
end
It's not clear how created_at
factors in here. Are these assigned daily? If so, that should be something like bank_date
as a DATE
type column, not date and time. Using the created_at
timestamp as part of the relationship is asking for trouble, that should reflect when the record was created, nothing more.
Upvotes: 1