Jordan Shefner
Jordan Shefner

Reputation: 135

Rails accessing all relations with deep nesting

I have the following models:

class Kid < ApplicationRecord
  belongs_to :group, optional: true

class Group < ApplicationRecord
  has_many :kids
  belongs_to :head

class Head < ApplicationRecord
  has_many :groups
  belongs_to :axis

class Axis < ApplicationRecord
  has_many :heads

What I've been trying to do is get all the kids of a head and of an axis (for example: @axis.kids would give all the kids, like @group.kids does). I tried some class methods with loops and arrays, but no luck so far. Any idea how to do this? Thanks!

Using rails 5.2

Edit: I got all the head's kids with

def kids
 Kid.where(group_id: self.groups.map(&:id))
end

But still haven't managed to get the axis' kids

Upvotes: 1

Views: 83

Answers (2)

itay ariely
itay ariely

Reputation: 11

Try to add this: has_many :kids, through: :heads In axis.rb

Upvotes: 1

Smek
Smek

Reputation: 1208

In Head you can add:

has_many :kids, through: :groups

Then you can do something like:

@head.kids

See the Rails docs

Upvotes: 3

Related Questions