在我的种子文件中创建记录之前如何检查记录?

How can I check for a record before creating it in my seeds file?

我的 Rails 种子文件如下所示...

  Club.create([
       {name: 'Atlanta Falcons', moniker: 'Falcons', city: 'Atlanta', state: 'GA', zipcode: '0', code: 'ATL', conference: 'NFC', division: 'South', primary_color: 'BD0D18', secondary_color: '000000', tertiary_color: 'FFFFFF', quaternary_color: 'DCE0E5', quinary_color: '', weather_location: 'Atlanta+GA+USGA0028:1:US', plays_in_dome: '1', time_zone: 'Eastern Time (US & Canada)', logo_image: 'atl.gif', word_art_image: 'title.gif', club_key: '4909', stadium_name: 'Georgia Dome', mini_image: 'atl.png'},
       {name: 'Buffalo Bills', moniker: 'Bills', city: 'Buffalo', state: 'NY', zipcode: '0', code: 'BUF', conference: 'AFC', division: 'East', primary_color: '00338D', secondary_color: 'C60C30', tertiary_color: 'FFFFFF', quaternary_color: '', quinary_color: '', weather_location: 'Buffalo+NY+USNY0181:1:US', plays_in_dome: '0', time_zone: 'Eastern Time (US & Canada)', logo_image: 'buf.gif', word_art_image: 'bil_ltyp_blu_pms.png', club_key: '4910', stadium_name: 'Ralph Wilson Stadium', mini_image: 'buf.png'}
    )]

我如何使用哈希数组执行此操作并仍然检查记录并且如果它们已经存在则不创建它们以避免重复?我只是想让验证抛出重复项;但是,这似乎不正确。谢谢!

由于这太大而无法放入评论中,因此您可以将其作为答案:

rows = [
   {name: 'Atlanta Falcons', moniker: 'Falcons', city: 'Atlanta', state: 'GA', zipcode: '0', code: 'ATL', conference: 'NFC', division: 'South', primary_color: 'BD0D18', secondary_color: '000000', tertiary_color: 'FFFFFF', quaternary_color: 'DCE0E5', quinary_color: '', weather_location: 'Atlanta+GA+USGA0028:1:US', plays_in_dome: '1', time_zone: 'Eastern Time (US & Canada)', logo_image: 'atl.gif', word_art_image: 'title.gif', club_key: '4909', stadium_name: 'Georgia Dome', mini_image: 'atl.png'},
   {name: 'Buffalo Bills', moniker: 'Bills', city: 'Buffalo', state: 'NY', zipcode: '0', code: 'BUF', conference: 'AFC', division: 'East', primary_color: '00338D', secondary_color: 'C60C30', tertiary_color: 'FFFFFF', quaternary_color: '', quinary_color: '', weather_location: 'Buffalo+NY+USNY0181:1:US', plays_in_dome: '0', time_zone: 'Eastern Time (US & Canada)', logo_image: 'buf.gif', word_art_image: 'bil_ltyp_blu_pms.png', club_key: '4910', stadium_name: 'Ralph Wilson Stadium', mini_image: 'buf.png'}
]

rows.each do |row|
  Club.where(club_key: row[:club_key]).first_or_create(row)
end

因此,对于每一行,如果该行存在,则仅 return 数据库中的记录,否则将创建它。

您可以找到有关 first_or_create

的更多信息
# File activerecord/lib/active_record/relation.rb, line 149
def first_or_create(attributes = nil, &block) # :nodoc:
  first || create(attributes, &block)
end

如果您不想使用 first_or_create,您可以使用 exists? 检查对象是否存在,如下所示:

rows.each do |row|
  unless Club.exists?(club_key: code[:club_key])
    Club.create(row)
  end 
end

但是,由于这比较冗长,您应该坚持使用 first_or_create 以更加简洁。我添加这个只是为了提供一个替代方案。