Allows us to work with the data between our models and tables in an object oriented way.
Relational Database Association:
One-to-One (not used often)
Note to remove the association you can assign nil to it
And to remove the associated record from the database .destroy
One-to-Many (used most often)
belong\_to is where the foreign key goes
subject.pages << page #append operator, since pages is a collection of objects
subject.pages = [page, page, page] #you can use equal operator, but you need to provide an array of values
subject.pages.delete(page) #removes the relationship, but does not delete the associated record
subject.pages.destroy(page) #removes the relationship and deletes the associated record
subject.pages.clear #removes the relationships, but not the records
has\_many and belongs\_to/has\_many and belongs\_to = has\_and\_belongs\_to\_many
utilizes a joined table (WITH NO ID: , :id => false in it's migration)
Join Table Naming Convention
E.g.: BlogPost - Category => BlogPost_Category
Many-to-Many (Rich Joins)
has a Joined table with extra rows
Use a descriptive name (no following many-to-many Rails conventions)
require a model (rail generate model [YourModelName])
requires an id for the model
remember to add foreign keys to tables that you want to join
add an index on the combined foreign keys
has\_many/has\_many = belong\_to + belongs\_to
has\_many on the tables to be joined
belongs\_to + belongs\_to on the connecting table (remember, belong\_to goes where the foreign key is)
Note: you can have a different name for the relationship field in your model file, if you specify the way to find the original, E.g.: belongs_to: editor :class_name => "AdminUser", :foreign_key => "admin_user_id". Belongs_to requires a :foreign_key to be specified as well as :class_name.
Note: use .reload on the ActiveRelation object to update it from the db.
Allows "reaching across" a rich join, treating it like an HABTM join
AdminUser has_many :sections, :through => :section_edits
Section has_many :admin_users, :through => :section_edits
_**Note: ** All the differences between Simple Many-to-Many and Rich Many-to-Many is that the later has a fully functional MODEL._