From 3bff80192aa4a22acec6d2aa06b7d5731de067ed Mon Sep 17 00:00:00 2001 From: kinseyost Date: Mon, 26 Sep 2016 21:16:33 -0700 Subject: [PATCH] One to Many Example --- Tutorial_Docs/Associations.MD | 14 ++++++++++++++ app/models/page.rb | 3 +++ app/models/subject.rb | 3 +++ 3 files changed, 20 insertions(+) create mode 100644 Tutorial_Docs/Associations.MD diff --git a/Tutorial_Docs/Associations.MD b/Tutorial_Docs/Associations.MD new file mode 100644 index 0000000..c0d3405 --- /dev/null +++ b/Tutorial_Docs/Associations.MD @@ -0,0 +1,14 @@ +# ActiveRecord Associations + +## One-to-one +* has_one +* belongs_to + +## One-to-many +* has_many +* belongs_to + +## Many to Many +(When join table only has foreign keys) +* has_and_belongs_to_many (HABTM method) +* has_and_belongs_to_many diff --git a/app/models/page.rb b/app/models/page.rb index ee51575..176ee1d 100644 --- a/app/models/page.rb +++ b/app/models/page.rb @@ -1,2 +1,5 @@ class Page < ApplicationRecord + + belongs_to :subject + end diff --git a/app/models/subject.rb b/app/models/subject.rb index 6b29eef..4a7f26b 100644 --- a/app/models/subject.rb +++ b/app/models/subject.rb @@ -1,5 +1,8 @@ class Subject < ApplicationRecord + # Relations + has_one :page # Doesn't actually have 1, but showing for demonstration purposes + # Lamda is read at execution time, which is important for dates. scope :visible, lambda { where(:visible => true) } # Stabby lambda syntax is subtly different, but can also be used.