Here is an example of some code we can refactor.

1) A clunky version.

  def self.populate!
    sections = Course.pluck(:section)
    available_courses = sections.uniq!
    available_courses.each do |name|
      Track.create(name: name)
    end
  end

2) Let’s reduce some lines

  def self.populate!
    Course.pluck(:section).uniq.each do |name|
      Track.create(name: name)
    end
  end

But… What if our uniq constraint is hit in the DB?

3) The following will add new records but silently fail on duplicate attempts in the Track model.

  def self.populate!
    Course.pluck(:section).uniq.each do |name|
      begin
        Track.create(name: name)
      rescue ActiveRecord::RecordNotUnique => e
        next if(e.message =~ /unique.*constraint.*name/)
        raise "Something else happened #{e}"
      end
    end
  end

🙂

Leave a Reply

Screen Shot 2013-12-08 at 9.49.35 PM

I have helped a dozen companies build and optimize their engineering teams to deliver great products.

Let’s work together and I can align your business needs with your technology initiatives.