What is ActiveRecord and Relationship Associations
Rather than utilize SQL to communicate with a database manually or have to manually tell an object which other object it belongs to upon each instantiation, ActiveRecord does that for you automatically in a sense and let’s you interact with that object as if it were another ruby object. All the developer has to do is appropriately set up it’s relationship associations. ActiveRecord has six relationship associations, amongst these are a “has_many”, “belongs_to”, and “belongs_to :through.”
has_many and belongs_to
The has_many and belongs_to relationship associations are fairly simple to comprehend once you’re able to tie them to actual things in the real world. As a developer you want to be able to ask yourself what kinds of relationships the models in your program have to one another and what makes sense logically. For example a pet model may typically only have one owner but an owner model might have many pets. I think the easiest way to understand these associations is by thinking of these kinds of relationships in reference to real life objects. Such as an author having many books but a book belonging to only one author. Or a film director having many films and a film belonging to a director.
Primary key and Foreign Key
Similar to SQL, ActiveRecord will use an integer column called id and automatically assign it a primary key upon migration which increments automatically upon each instantiation of a new object and when creating associations between models ActiveRecord will look for foreign keys that have to be included in the table of its desired associated model ie; user_id, item_id, order_id). For example if I wanted a user model to be associated with an order model I would add a user_id column to it’s order table.
Since models in Sinatra are pretty much Ruby files that inherit from ActiveRecord. This allows models to utilize useful methods like .all, .find, .update, .create, .delete, and more. This is pretty powerful because it allows the developer to focus on writing code versus figuring out how to connect to the database.
Comments
Post a Comment