My 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'}
)]
如何使用哈希数组执行此操作并仍检查记录,如果已存在则不创建它们,以避免重复?我只是允许验证抛出重复项;然而,它似乎并不正确。谢谢!
答案 0 :(得分:2)
由于这个太大而无法放入评论中,因此您可以将其作为答案:
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
因此,对于每一行,如果该行存在,则只返回数据库中的记录,否则将创建它。
您可以找到有关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来更简洁。我添加这个只是为了提供一个替代方案。