ActiveRecord Model Equality
In daily web app development, we often need to check if two model objects are equal. When I first started using Rails, this is what I wrote:
Use obj1 == obj2 instead
Of course, that reflects my ignorance on learning the new tool.
So, here’s a proper way to compare if two model objects are equal:
What about new record?
Basically, a new model object only equals to itself:
Learning to use ==
operator for checking model equality
is useful. Because now, we can start using other methods
that depend on ==
operator. For instance, Array#include?
.
Rails learning tests
You may notice the code examples are written as tests. This is my first Rails learning test. So the plan is to write more tests as a way to learn Rails. I will post them here occationally if interesting enough to share.
Source code: model_equality_test.rb