Ruby on Rails - Get records from grandchild table

Viewed 99

I have 3 tables like so (This is just a simplified example of what my table actually is):

Table #1 is titled Parent, and its only got two fields: ID and Name.

Humans has many children. Table #2 is therefore Childrens and its got parent_id and other unimportant fields.

Childrens has many friends. Table #3 is Friends and its got children_id and other unimportant fields.

Basically, given only the parent_id which let's say is 1, I want to return all values from the Friends table such that they are the friends of that single parent's children. I guess I'd have to iterate through the Childrens tables and get all children_id where parent_id = 1. And than I'd iterate through Friends and match on the previously collected children_id. Can someone show me if there's a good way of doing this in ruby on rails. I'm using postgresql.

1 Answers

Use has_many :friends, through: :children

class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
  has_many :friends, through: :children
end

class Child < ApplicationRecord
  belongs_to :parent
  has_many :friends, dependent: :destroy
end

class Friend < ApplicationRecord
  belongs_to :child
end

Then you can access all friends like this

parent.friends
Related