When working in Rails, polymorphic association offers a way to have a model belong to multiple models through an association — this is accomplished by allowing you to choose what model you select a foreign key from. If you’re wondering ‘how does that work?’ and ‘what would that look like?’, well, you came to the right place!

Preface

While there are more concise ways of demonstrating this example, I thought a step-by-step walkthrough would help give context to the association. So, to illustrate how this works, we’re going to start a new project: as our example, we’ll be using the presidential…


What started as a Flatiron exercise in creating custom validations ended in confusion when the solution included this:

CLICKBAIT_PATTERNS = [
/Won’t Believe/i,
/Secret/i,
/Top [0–9]*/i,
/Guess/i
]
def is_clickbait?
if CLICKBAIT_PATTERNS.none? { |pat| pat.match title }
errors.add(:title, “must be clickbait”)
end
end

This innocuous block of code bewildered me because I had yet to venture into regular expressions (admittedly, I didn’t even know at the time that it was a regular expression, even if only in part). After just a little bit of research I learned that this is about as simple as it gets for regexes, but my…


Arguments vs Parameters

While the term ‘argument’ can be used in place of ‘parameter’ (and it often is), the distinction between the two is worth noting. If an argument is a value that is passed into a method, then the parameter is simply a placeholder for the argument in the definition of the method. We can boil down the differences to this:

  • Parameters have no inherent value and are established with the definition of a method;
  • Arguments contain a value and are passed into a method.

If you’ve ever done mad libs, parameters and arguments work in a similar way…

Evan Fujita

Software Engineering Student @ Flatiron Chicago

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store