From de2175ce16242dd1b9f9e2dd95d01c018302fd7a Mon Sep 17 00:00:00 2001 From: Brenda Wallace Date: Tue, 16 Oct 2018 13:20:03 +1300 Subject: [PATCH] More inverse relationships defined --- app/models/garden.rb | 2 +- app/models/photo.rb | 3 ++- app/models/photographing.rb | 2 +- app/models/planting.rb | 12 ++++++++---- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/app/models/garden.rb b/app/models/garden.rb index 9687982cb..01466120f 100644 --- a/app/models/garden.rb +++ b/app/models/garden.rb @@ -62,7 +62,7 @@ class Garden < ApplicationRecord unique_plantings = [] seen_crops = [] - plantings.order(created_at: :desc).includes(:garden, :crop, :owner, :harvests).each do |p| + plantings.includes(:garden, :crop, :owner, :harvests).order(created_at: :desc).each do |p| unless seen_crops.include?(p.crop) unique_plantings.push(p) seen_crops.push(p.crop) diff --git a/app/models/photo.rb b/app/models/photo.rb index 69a30d245..f3636760c 100644 --- a/app/models/photo.rb +++ b/app/models/photo.rb @@ -3,7 +3,8 @@ class Photo < ApplicationRecord PHOTO_CAPABLE = %w(Garden Planting Harvest Seed).freeze - has_many :photographings, foreign_key: :photo_id, dependent: :destroy + has_many :photographings, foreign_key: :photo_id, dependent: :destroy, inverse_of: :photo + # creates a relationship for each assignee type PHOTO_CAPABLE.each do |type| has_many type.downcase.pluralize.to_s.to_sym, diff --git a/app/models/photographing.rb b/app/models/photographing.rb index 040817611..b62ed10e6 100644 --- a/app/models/photographing.rb +++ b/app/models/photographing.rb @@ -1,5 +1,5 @@ class Photographing < ApplicationRecord - belongs_to :photo + belongs_to :photo, inverse_of: :photographings belongs_to :photographable, polymorphic: true validate :photo_and_item_have_same_owner diff --git a/app/models/planting.rb b/app/models/planting.rb index 61b75e326..27f99870b 100644 --- a/app/models/planting.rb +++ b/app/models/planting.rb @@ -21,10 +21,14 @@ class Planting < ApplicationRecord # # Ancestry of food - belongs_to :parent_seed, class_name: 'Seed', foreign_key: 'parent_seed_id', - required: false # parent - has_many :child_seeds, class_name: 'Seed', - foreign_key: 'parent_planting_id', dependent: :nullify # children + belongs_to :parent_seed, class_name: 'Seed', # parent + foreign_key: 'parent_seed_id', + required: false, + inverse_of: :child_plantings + has_many :child_seeds, class_name: 'Seed', # children + foreign_key: 'parent_planting_id', + inverse_of: :parent_planting, + dependent: :nullify ## ## Scopes