在我的Rails应用程序中,我已经在预订模型中创建了一个CSV文件。
def self.to_excel
attributes = %w{ name email mobile address transaction_id price deposit paid booked_by date}
CSV.generate(headers: true) do |csv|
csv << attributes
where('date(created_at) = ?', Date.today).each do |booking|
csv << attributes.map{ |attr| booking.send(attr) }
end
end
end
预订控制器
def index
respond_to do |format|
format.html
format.csv { send_data @bookings.to_excel, filename: "Booking-#{Date.today}.csv" }
end
end
邮件程序
class CsvMailer < ApplicationMailer
default from: "xyz@gmail.com"
def send_csv(booking)
@booking = booking
attachments['Booking.csv'] = {mime_type: 'text/csv', content: csv}
mail(to: "xyz@gmail.com", subject: "Booking Details-#{Date.today}.csv")
end
end
我需要每24小时发送一次自动生成的csv文件,并附上当天预订的详细信息。这应该只生成csv并通过mailer邮寄。我该如何进行。谁能帮忙。
答案 0 :(得分:0)
如果要每24小时发送一次电子邮件,则需要实施cron作业。
请检查gem whenever,它用于导轨中的cron作业
在schedule.rb
every :day, at: '12:00am' do
runner "Booking.send_csv"
end
在send_csv方法中,生成CSV文件,然后将其发送给以下类似的邮件
class Booking
def generate_csv
bookings = create query for fetching today's bookings
csv = bookings.to_excel
CsvMailer.send_csv(user, csv).deliver
end
end
答案 1 :(得分:0)
您可以使用Arask进行最少的设置。安装gem并初始化文件,并将其放入config / initializers / arask.rb
arask.create script: 'Booking.send_csv', cron: '0 0 * * *'
并重用@vishal代码:
class Booking
def generate_csv
bookings = create query for fetching todays bookings
csv = bookings.to_excel
CsvMailer.send_csv(user, csv).deliver
end
end