Skip to content

Instantly share code, notes, and snippets.

@EdgarOrtegaRamirez
Last active July 25, 2019 15:19
Show Gist options
  • Save EdgarOrtegaRamirez/cb93317832b69e49568f4e0b03b0091b to your computer and use it in GitHub Desktop.
Save EdgarOrtegaRamirez/cb93317832b69e49568f4e0b03b0091b to your computer and use it in GitHub Desktop.
Rails deep nested associations
➜ bin/rails c
Loading development environment (Rails 5.2.3)
2.6.2 :001 > class Profile < ApplicationRecord
2.6.2 :002?> has_many :persons, inverse_of: :profile, dependent: :destroy
2.6.2 :003?> has_many :foos, :through => :persons
2.6.2 :005?> accepts_nested_attributes_for :persons
2.6.2 :006?> end
=> [:persons]
2.6.2 :007 > class Person < ApplicationRecord
2.6.2 :008?> has_one :foo, inverse_of: :person, dependent: :destroy
2.6.2 :009?> has_one :bar, :through => :foo
2.6.2 :011?> belongs_to :profile, inverse_of: :persons
2.6.2 :012?> belongs_to :person_type
2.6.2 :014?> accepts_nested_attributes_for :foo
2.6.2 :015?> end
=> [:foo]
2.6.2 :016 > class Foo < ApplicationRecord
2.6.2 :017?> has_one :bar, inverse_of: :foo
2.6.2 :018?> belongs_to :person # you are missing this
2.6.2 :019?> end
=> {"bar"=>#<ActiveRecord::Reflection::HasOneReflection:0x00007f9ae02a9090 ...}
2.6.2 :020 > class Bar < ApplicationRecord
2.6.2 :021?> belongs_to :foo, inverse_of: :bar
2.6.2 :022?> end
=> {"foo"=>#<ActiveRecord::Reflection::BelongsToReflection:0x00007f9ae02fb5c0 ...}
2.6.2 :023 > profile = Profile.new
=> #<Profile id: nil>
2.6.2 :024 > person = profile.persons.build
=> #<Person id: nil, profile_id: nil>
2.6.2 :025 > foo = person.build_foo
=> #<Foo id: nil, person_id: nil>
2.6.2 :026 > foo.build_bar
=> #<Bar id: nil, foo_id: nil>
2.6.2 :028 > profile.persons[0].foo.bar
=> #<Bar id: nil, foo_id: nil>
2.6.2 :030 > profile.save
(0.3ms) BEGIN
Profile Create (1.1ms) INSERT INTO "profiles" DEFAULT VALUES RETURNING "id"
Person Create (0.7ms) INSERT INTO "people" ("profile_id") VALUES ($1) RETURNING "id" [["profile_id", 2]]
Foo Create (0.5ms) INSERT INTO "foos" ("person_id") VALUES ($1) RETURNING "id" [["person_id", 2]]
Bar Create (0.7ms) INSERT INTO "bars" ("foo_id") VALUES ($1) RETURNING "id" [["foo_id", 2]]
(5.6ms) COMMIT
=> true
CREATE TABLE public.profiles (
id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,
CONSTRAINT profiles_pk PRIMARY KEY (id)
);
CREATE TABLE public.people (
id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,
profile_id int4 NOT NULL,
CONSTRAINT people_pk PRIMARY KEY (id)
);
CREATE TABLE public.foos (
id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,
person_id int4 NOT NULL,
CONSTRAINT foos_pk PRIMARY KEY (id)
);
CREATE TABLE public.bars (
id int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY,
foo_id int4 NOT NULL,
CONSTRAINT bars_pk PRIMARY KEY (id)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment