目前我正在通过屏幕抓取来抓取足球赛程,每次执行 rake 任务时,我都会删除所有记录并保存新记录。我不想这样做,我只想保存不存在的赛程. 到目前为止我的逻辑是
def get_fixtures # Get me all Home and away Teams
doc = Nokogiri::HTML(open(FIXTURE_URL))
days = doc.css('#fixtures-data h2').each do |h2_tag|
date = Date.parse(h2_tag.text.strip).to_date
matches = h2_tag.xpath('following-sibling::*[1]').css('tr.preview')
matches.each do |match|
home_team = match.css('.team-home').text.strip
away_team = match.css('.team-away').text.strip
kick_off = match.css('td.kickoff').text.strip
Fixture.create!(home_team: home_team, away_team: away_team, fixture_date: date, kickoff_time: kick_off)
end
end
结尾
最好的方法是什么,另一种检查记录是否存在的方法?但不确定如何去做
我的夹具模型
class Fixture < ActiveRecord::Base
attr_accessible :home_team, :away_team, :fixture_date, :kickoff_time, :prediction_id
belongs_to :predictions
end
我可以在夹具模型中使用 validates_uniqueness_of 吗,我在 rake 任务中的创建会先检查这个吗?
任何帮助表示赞赏