two many to many timber app

Post on 07-Jul-2015

273 Views

Category:

Internet

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Building Timber with Many To Many Associations

TRANSCRIPT

Timber App: Two Many To Many

Ruby Rails Associations@PareidoliaX

Three Take Homes1. 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.

Timber Iteration 1Requirements

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

Timber Iteration 2NEW Requirement

4 A Lumberjack or Lumberjill can make a hot list

Today's Association:4 has_many through:

4 has_and_belongs_to_many

Based on the Many to Many database relationship4 Requires a Join Table which saves the belongs_to

data.

Things will a little be weird

LumberJack's use has_and_belongs_to_many

They are simpler and less flexible.

LumberJack Join Table Migrationclass 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 endend

LumberJack Modelclass Lumberjack < ActiveRecord::Base belongs_to :lumberjill has_many :lumberjills

has_and_belongs_to_many :hotties, class_name: 'Lumberjill'end

LumberJack Seedputs "Adding hotties to lumberjacks"lumberjacks.each do |lumberjack| rand(2..7).times do lumberjack.hotties << lumberjills.sample end print lumberjack.hotties.pluck(:id).to_send

LumberJill's use has_many :throughThey are more flexible and complicated.

LumberJill Join Table Migrationclass 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 endend

LumberJill Modelclass Lumberjill < ActiveRecord::Base belongs_to :lumberjack has_many :lumberjacks

has_many :hots has_many :hotties, through: :hots, source: :lumberjackend

LumberJill Seedputs "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_send

Three Take Homes1. 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.

Find Me4 Twitter: @pareidoliax

4 Website: pareidoliax.ca

4 Github: pareidoliax

4 email: xander.miller@gmail.com

top related