I have three tables parents, children and fundings.
parent.rb
class Parent < ApplicationRecord
has_many :children, dependent: :destroy
end
child.rb
class Parent < ApplicationRecord
belongs_to :parent
has_many :fundings, dependent: :destroy
end
funding.rb
class Funding < ApplicationRecord
belongs_to :child
end
Joins between children and fundings
create_table "children_fundings", id: false, force: :cascade do |t|
t.integer "child_id", null: false
t.integer "funding_id", null: false
t.index ["child_id", "funding_id"], name:
"index_children_fundings_on_child_id_and_funding_id"
t.index ["funding_id", "child_id"], name:
"index_children_fundings_on_funding_id_and_child_id"
end
join between children and parents
create_table "children_parents", id: false, force: :cascade do |t|
t.integer "parent_id", null: false
t.integer "child_id", null: false
t.index ["child_id", "parent_id"], name:
"index_children_parents_on_child_id_and_parent_id"
t.index ["parent_id", "child_id"], name:
"index_children_parents_on_parent_id_and_child_id"
end
children table has parent_id, fundings table has child_id. How can I create a join between parents children and fundings table. Please help
You don't need join tables here - rather a parent ID column on the child record. So, in your case:
Childneeds an integer columnparent_idFundingneeds an integer columnchild_idJoin tables only come into play when you're implementing a
has_and_belongs_to_manyorhas_many throughrelationship.If you think about how you tie the records together, for a child to belong to a parent, the child merely needs to know which parent its tied to, hence the column.
Now, imagine parents had many children, children had many parents: a single parent ID wouldn't cut it, so the join table comes in to tie the two together, containing (for example) both
parent_idandchild_idin each row of data.The database ties the records together using these methods, querying the id or join table as needed.
To access the fundings from the parent record, you can either link the two together if their independently related, or access via the children if not.
For the latter, you can use something like the following.
In your controller:
In your view:
That's a little messy, so it would be worth separating the data in the controller or partials as suits. Hope that gives you an idea of how to work this though?