Subqueries in ActiveRecord with Multiple Conditions & Distinct Select

I’ve recently started learning about database subqueries and how to do them with ActiveRecord. I’ve also learned a cool new formatting trick (at least using RubyMine IDE).

This is the beginning of my learning so don’t take this as great code. In fact, this is really here so I don’t forget it and it’s easily available the next time I need it (and I can work on making it better then).

In other words, this code is for me, not you. 🙂

start_day = DateTime.new(2017)
customers = Customer.where(id: WorkOrder
                                   .where(id: Payment
                                                  .where('location_id = 2 and payment_received_date >= ?', start_day)
                                                  .select(:work_order_id)
                                                  .uniq)
                                   .where("orderable_type = 'Customer'")
                                   .select(:orderable_id)
                                   .uniq)
customers.update_all(special_contact_required: true)

What it Does

I needed to email a subset of our customers that…

  1. … paid for a repair on or after January 1, 2017 at one of our specific stores.
    • .where(‘location_id = 2 and payment_received_date >= ?’, start_day)
  2. … were an actual customer and not a business.
    • .where(“orderable_type = ‘Customer'”)

Things to Know

  1. Written for Rails 3.2 so it uses .uniq instead of .distinct (.uniq is deprecated).
  2. The initial .where operation becomes a single query when it’s executed.
  3. Combing the .where with .update_all means only two total queries were needed to grab the records I wanted and update them.
  4. The indented formatting starting with . (dot) makes it easy to build and read these subqueries. I love this formatting style.

Things to Learn

  1. I couldn’t figure out a way to do the .select together with a .order. It wasn’t a big deal in this case (it was part of a migration), but in the future it will be necessary to sort them.

Ask Your Self This Question Regularly

What makes me believe I’m right?

We should all ask ourselves that question much more often than we do. Consider the following simple yet powerful hypothesis:

  1. I believe I’m right about the things I believe.
  2. I’m not 100% right about everything I believe.
  3. Therefore: I am wrong about some of the things I believe.

Reasonable people will agree with me. Honestly, I think this argument is infallible. How’s that for irony. 🙂

The problem is we don’t know which of our beliefs are wrong. We wouldn’t believe them if we did. A better question to ask than, “Am I right?” (and far better than insisting, “I’m right!”):

What makes me believe I’m right?

In answering this question we can start to evaluate our beliefs. We can help others evaluate their beliefs by asking:

What makes you believe you’re right?

The answer to this question will tell you how deeply they’ve thought about it. And if you’re a thoughtful person that disagrees with them, you may just find their argument more convincing than yours.

I Prefer Emerson’s Philosophy

The other day I heard someone saying how dumb the average person is and how half the population is even dumber than that.

This is arrogance infused with ignorance.

Emerson said it best: “Every man is my superior in some way and therefore worthy of my respect.”

(Aside: If Emerson were alive and writing today my hope is he would have actually said: “Every man and woman…”)

Don’t ever think you’re smarter than the average person because you’re not. At least not in many ways. If she’s a plumber, she knows a lot more than you about how to fix a broken toilet. Or maybe it’s an electrician who knows how to keep your house lit at night and the furnace running. Modern life wouldn’t move forward without either.

Remember this: You are far, far more ignorant about the world than you are knowledgeable.

15 Minutes a Day for More Knowledge

In 15 minutes a day you can learn more than most people learn in 4 years of college.

For the past year I’ve started each workday making a cup of coffee and spending 15 minutes reading something dense. In that time I’ve finished over 1500 pages worth of incredible material. Here’s a few of those books:

This may sound like dry and boring material and at times it is. But the fact is, anyone can sit down and read something truly deep and important for 15 minutes a day. It’s sort of like the Colorado river carving out the Grand Canyon. From day-to-day you may not see a perceptible difference in the landscape but over time something truly magnificent happens.

Caveat about Economics

My last post was about how important it is to learn about economics. I stand by that statement but also offer a warning. Traditional economics considers humans like robots that can gather and consider all the data instantly and then make purely rational and correct decisions.

That is not how humans are built.

Two simple examples:

  1. Think of the last time you were really angry. Did you make rational decisions?
  2. Have you bought a used car (or anything used)? Did you know everything about the condition of the car so you could properly factor the risks of ownership into the cost?

The answer to both is obviously, “No.” We are not always rational nor do we always have access to all the relevant information for decision making.

Economics is great to know. Truly it is. But spend time studying and learning about human psychology as well. Combining psychology and economics is a powerful framework for making decisions and understanding the world.

Why You Should Read a Microeconomics Textbook

A Good Economics Textbook

A Good Economics Textbook

One of the deficiencies of my college education was not taking an economics course. I recently fixed that by spending 15 minutes each morning reading Principles of Microeconomics by Gregory Mankiw. Everyone should read this book (or something similar). Microeconomics is mostly common sense but, unfortunately, it seems that too many people – especially our politicians – don’t know these lessons.

Short aside: It’s amazing how much you can learn by just reading 15 minutes a day. In this case, it took me about six weeks to read a 500 page textbook that will be useful for the rest of my life.

Continue reading

My Most Important Piece of Advice

Never Stop Learning

I’ve toyed with blogging several times but never hit on a theme that really resonated with me – until now. I have a big reason to blog – two reasons in fact: Theo and Jonah. My two little boys that inspire me every day to be and do better.

This blog is dedicated to them. Or more specifically, my attempting to teach them some of the the things I think I’ve learned so far.

In this first post I want to share what I think is the most important thing someone can do to be successful and happy in life: stay curious and keep learning.

Fortunately, this is not something limited to school. You can be curious and learn for your entire life. That’s what makes it so great. Here are just a few of the things you can do:

  1. Go to school and pay attention.
  2. Read books – especially non-fiction.
  3. Listen to podcasts.
  4. Watch documentaries.
  5. Talk to other people about what they know.
  6. Ask people to challenge your beliefs, and don’t get mad when they do.
  7. Take the time to observe the world.
  8. Just think about things. You can sit quietly or, my favorite, go for a run.
  9. Ask, “Why,” a lot.

That last item may be the most important. It shows the root of learning: curiosity. Don’t just be curious about your corner of the world. Be curious about everything. It’s fun to learn something new. Beside, you never know when it might be relevant to your life.

A simple example: prime numbers. 50 years ago calculating large prime numbers may have seemed nothing but a bit of fun for weird mathematicians. Not really an important part of life. Then came e-commerce in the mid-90s. Suddenly people wanted to send their personal and credit card information over the web, but they didn’t want the wrong people seeing it. Guess what? It turns out that large prime numbers are the foundation of online encryption. What was once just mathematical gymnastics turns out to be the lifeblood of a new technology.

The world is full of similar examples of seemingly trivial information becoming very important and valuable as technology and life change – and they will continue to change.

So, Theo & Jonah, please, stay curious. Please take the time to follow where that curiosity leads. Learn. It will not only lead you to success but, I believe, show you the path to a happy and fulfilling life.

Love, Dad.