追加する
から
departments = ["this", "that"]
departments.each{|d| Department.where(:name => d).first_or_create}
に
departments = ["this", "that", "there", "then"]
departments.each{|d| Department.where(:name => d).first_or_create}
これは簡単な例です。
更新/名前変更
から
departments = ["this", "that", "there", "then"]
departments.each{|d| Department.where(:name => d).first_or_create}
に
departments = ["these", "those", "there", "then"]
new_names = [['these', 'this'],['those','that']]
new_names.each do |new|
Department.where(:name => new).group_by(&:name).each do |name, depts|
depts.first.update_column :name, new[0] if new[1] == name # skips validation
# depts[1..-1].each(&:destroy) if depts.size > 1 # paranoid mode
end
end
departments.each{|d| Department.where(:name => d).first_or_create}
重要:配列の要素を更新する必要があります。そうしないと、departments
確実に重複が発生します。
回避策: validates_uniqueness_of 検証または必要なすべての属性を比較する一意性の検証を追加しますが、検証をスキップするメソッドは使用しないでください。