Revisiting ActiveRecord Associations
The endeavor of this week has been to update the back end of my DreamBean application (adding a User resource, implementing table associations, password encryption, and other validations), I am enjoying revisiting the realm of Rails and the powerful capabilities of ActiveRecord macros.
As I was creating for a relationship for my user to be able to select multiple beans for purchase, the relationship I employed was a has_many association from the user model to the bean model, and a belongs_to association from the Bean model to the user model. I would like to emphasize how much that these macros can do for you in regards to manipulating a data table with ActiveRecord class methods, giving you full CRUD functionality with just a few class methods( i.e destroy for deletion).
While these ActiveRecord associations are simple conceptually, the work that Rails does for you behind the scenes with these instructions is comprehensive. Simply by setting the belongs_to relationship in your models you are now instructing Rails to create primary and foreign key relationship in those respective data tables and inheriting class methods for queries and retrieval of data objects. All of this is streamlined with the sublime architecture of ActiveRecord and Rails.
The has_many :through relationship are when things get a bit more involved. A quick example of a has_many :through relationship. My user table could have many bean_origins through the joined association of beans table.This is a clunky example and the analogy of doctors, appointments, and patients is much better, but this is an example relevant to my project. I always remember it as a triangle. For an excellent resource for learning about them click here https://gabi.dev/2017/08/08/activerecord-has-many-through-through-relationship/
Rails is sleek and it is poetically efficient. Doing so much with so little feels strange at times, but it serves as a fuel for me to do my research in order to understand exactly what is making all the cogs work behind the scenes. It as is smooth as it is intricate.