Active Record associations are a convenient way to declare methods through different models, from your database to columns and tables.
These examples are based on my last sinatra project with Flatiron School.
class Pet < ActiveRecord::Base
belongs_to :user
end
- This is displayed as a singular.
- Sets up a one on one connection with another Model, in this case PETS to USER
- Uses a foreign key user_id
METHODS ADDED BY BELONGS_TO
.association=(associate)
The association= assigns to associate (user) object to the
(pet) object which means extracting the primary key (user_id) from my table and setting the foreign key to the same value.
Pets | User |
---|---|
user_id | username |
name | password |
age | |
notes |
This table above is an explanation of how my tables are a ONE to ONE relationship as the record contains exactly one instance of another Model.
.build.association(attribute={})
This association returns a new object of the associated type. The object will be an instance from the passed attribute and the link through this object's foreign key will be set but
NOT SAVED.
.create_association
This association returns the new object of the associated type. It will be instantiated from the passed attributes,then linked to the object's foreign key, and finally be set. Once it passes validations it will BE SAVED.
HAS_MANY :PETS
class User < ActiveRecord::Base
has_many :pets
end
This is called the collection method and returns a relation of all the associated objects(pets). If there are no associated objects it will return an empty relation.
.collection(object)
This method makes the collection contain only the supplied objects by adding and deleting as appropriate. The changes are persisted to the database.
.collection.build(User.pets.build)
This method returns a single or an array of new objects of the associated type. The objects will be instantiated from the passed attributes and then linked through their foreign key which will be created but NOT SAVED.
.collection.create(User.pets.create)
This method will create a single or an array of new objects. The objects will be instantiated from the passed attributes, and then linked to the foreign key. Once it passes validations IT WILL BE SAVED.
Happy Coding!
Top comments (0)