仅保存不存在的记录

时间:2013-05-14 19:52:15

标签: ruby-on-rails ruby ruby-on-rails-3 model

目前我通过屏幕抓取抓住足球设备,每次执行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任务中创建会先检查吗?

任何帮助表示赞赏

2 个答案:

答案 0 :(得分:3)

有几种选择:

One Shot(截至Rails 3.2.13):

Fixture.where(home_team: home_team, away_team: away_team, fixture_date: date, kickoff_time: kick_off).first_or_create!

答案 1 :(得分:1)

您可以使用find_or_create_by_方法:

Fixture.find_or_create_by_home_team(home_team: home_team, away_team: away_team, fixture_date: date, kickoff_time: kick_off)

如果该对象尚不存在,则可以使用此动态查找器创建该对象。使用find_or_create_by_调用此动态查找程序,如果对象已经存在则将返回该对象,否则将创建该对象,然后返回该对象。

如果find_or_create_by_有其他参数,则必须将所有参数作为哈希传递。