1. Timber App: Two Many To
Many
Ruby Rails Associations
@PareidoliaX
2. Three Take Homes
1. Both has_many through: and has_and_belong_to_many
require a join table.
2. has_many through is more versitile than
has_and_belong_to_many but requires creating an
additional model.
3. Since there is no model has_and_belongs_to_many
requires you to manipulate the relationship as a
ActiveRecord collection.
3. Timber Iteration 1
Requirements
4 Tracks Lumberjacks and Lumberjills
4 A Lumberjack or Lumberjill can choose one true love
4 A Lumberjack or Lumberjill's profile shows all their
admires
4. Timber Iteration 2
NEW Requirement
4 A Lumberjack or Lumberjill can make a hot list
9. LumberJack Join Table Migration
class LumberjacksLumberjills < ActiveRecord::Migration
def change
create_table :lumberjacks_lumberjills, id: false do |t|
t.belongs_to :lumberjack, index: true
t.belongs_to :lumberjill, index: true
end
end
end
10. LumberJack Model
class Lumberjack < ActiveRecord::Base
belongs_to :lumberjill
has_many :lumberjills
has_and_belongs_to_many :hotties, class_name: 'Lumberjill'
end
11. LumberJack Seed
puts "Adding hotties to lumberjacks"
lumberjacks.each do |lumberjack|
rand(2..7).times do
lumberjack.hotties << lumberjills.sample
end
print lumberjack.hotties.pluck(:id).to_s
end
13. LumberJill Join Table Migration
class CreateHots < ActiveRecord::Migration
def change
create_table :hots do |t|
t.belongs_to :lumberjack, index: true
t.belongs_to :lumberjill, index: true
t.timestamps
end
end
end
14. LumberJill Model
class Lumberjill < ActiveRecord::Base
belongs_to :lumberjack
has_many :lumberjacks
has_many :hots
has_many :hotties, through: :hots, source: :lumberjack
end
15. LumberJill Seed
puts "Adding hotties to lumberjills"
lumberjills.each do |lumberjill|
rand(2..7).times do
lumberjill.hots.create lumberjack: lumberjacks.sample
end
print lumberjill.hotties.pluck(:id).to_s
end
16. Three Take Homes
1. Both has_many through: and has_and_belong_to_many
require a join table.
2. has_many through is more versitile than
has_and_belong_to_many but requires creating an
additional model.
3. Since there is no model has_and_belongs_to_many
requires you to manipulate the relationship as a
ActiveRecord collection.