Chapter 7 - Active Record Associations Flashcards
Add index
add_index :timesheets, :user_id
add_index :expense_reports, :user_id
pluck
Use pluck as a shortcut to select one or more attributes without loading a bunch of records just to grab the attributes you want.
Pluck returns an array.
has_many
the has_many association allows you to define a relationship in which one model has many other models that belong to it.
has_many :timesheets
has_many :expense_reports
One-To-Many
class User
where(*conditions)
has_many :pending_comments, -> { where( approved: true) }, class_name: ‘Comment’
has_and_belongs_to_many
I must clear my conscience by stating that
has_and_belongs_to_many is practically obsolete.
create_join_table
create_join_table :billing_codes, :timesheets
class Timesheet
has_many :through
The has_many :through association allows you to specify a one-to-many relationship indirectly via an intermediate join table. In fact, you can specify more than one such relationship via the same table, which effectively makes it a replacement for has_and_belongs_to_many. The biggest advantage is that the join table contains full-fledged model objects complete with primary keys and ancillary data.
has_many :through implementation
class Client
has_many :through as aggregating
class Grandparent
Join models and validations
You can add validates_uniqueness_of constraints on the join model to keep duplicate joins from happening.
validates_uniqueness_of :client_id, scope: :timesheet_id
One-to-One Relationship
One of the most basic relationship types is a one-to-one object relationship. In Active Record we declare a one-to-one relationship using the has_one and belongs_to methods together.
class User