我正在运行任务废弃网站以获得一些音乐会日期。
我的任务是查找/更新音乐会(日期和城市),并将其记录在数据库中。我可以在我的rails控制台中找到它们,也可以在我的索引和显示视图中显示它们。 顺便说一句,似乎它没有通过ConcertController中的create方法(我尝试使用binding.pry)
运行任务后,如果找到新记录,我想收到电子邮件提醒。当我收到电子邮件时,它没有完成:
concert_mailer / new_dates.html.erb
<p>The boys are playing at <%= @concert.city %> on <%= @concert.date %></p>
#returns The boys are playing at on
<p>The boys are playing at <%= @concert.inspect %> </p>
#returns: The boys are playing at <Concert id: 1, date: nil, city: nil, created_at: "2017-12-05 20:32:09", updated_at: "2017-12-05 20:32:09">
在rails控制台中,我有记录:
<Concert id: 1, date: "2017-12-08 00:00:00", city: "ECHANGE CULTUREL CAMEROUN (0) | au 18 décembre 20...", created_at: "2017-12-05 20:32:09", updated_at: "2017-12-05 20:32:10">
顺便说一句,这是我的任务:
namespace :scrap do
desc "This get MM concerts"
url = "http://mountain-men.fr/concerts/"
doc = Nokogiri::HTML(open(url))
data = doc.search('#dateconcert table')
data = data.css('.jaunec' ).map { |tr| tr.css('td').map(&:text) } + doc.css('.jaunef' ).map { |tr| tr.css('td').map(&:text) }
task :find_concerts => :environment do
data.each do |concert|
c = Concert.create!
c.date = concert[0]
c.city = concert[1]
c.save
end
end
task :update_concerts => :environment do
existing_date = Concert.all.map { |c| [c.date, c.city] }
data.each do |concert|
c = Concert.create!
c.date = concert[0]
c.city = concert[1]
c.save unless existing_date.include?([concert[0], concert[1]])
end
Concert.where(city: nil, date:nil).destroy_all
end
end
concert.rb
class Concert < ApplicationRecord
after_create :send_notification
def send_notification
ConcertMailer.new_dates(self).deliver_now
end
end
concert_mailer.rb
class ConcertMailer < ApplicationMailer
default from: "concert@mountain-men.fr"
def new_dates(concert)
@concert = concert
mail( to: "email@exemple.com",
subject: "The boys are back in town"
)
end
end
答案 0 :(得分:1)
在使用数据更新Concert
对象之前,正在调用触发电子邮件的after_create回调。在保存Concert
对象之前,请尝试向字段添加值,而不是创建空对象。
这样的事情:
data.each do |concert|
c = Concert.new
c.date = concert[0]
c.city = concert[1]
c.save
end
或者这个:
data.each do |concert|
Concert.create(date: concert[0], city: concert[1])
end
这样,您可以在触发after_create
回调之前保存值。