ruby on rails - Only save the records that don't exist -
currently grabbing football fixtures via screen scrape , each time rake task performed deleting records , saving new ones..i don't want this, want save fixtures dont exist. logic far
def get_fixtures # me home , away teams doc = nokogiri::html(open(fixture_url)) days = doc.css('#fixtures-data h2').each |h2_tag| date = date.parse(h2_tag.text.strip).to_date matches = h2_tag.xpath('following-sibling::*[1]').css('tr.preview') matches.each |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
end
what best way go this, method check if record exists? unsure how go this
my fixture model
class fixture < activerecord::base attr_accessible :home_team, :away_team, :fixture_date, :kickoff_time, :prediction_id belongs_to :predictions end
could use validates_uniqueness_of in fixture model, create in rake task check first?
any appreciated
several choices:
one shot (as of rails 3.2.13):
fixture.where(home_team: home_team, away_team: away_team, fixture_date: date, kickoff_time: kick_off).first_or_create!
Comments
Post a Comment