Reputation: 21
Is there any way I can get this SQL query by using ActiveRecord query syntax?
select t1.*
from
t1
join t2 on t1.id = t2.t1_id
join t3 on t2.id = t3.t2_id
join t4 on t3.id = t4.t3_id
join t5 on t4.id = t5.t4_id
where t5.id = 5;
Upvotes: 1
Views: 1178
Reputation: 9495
The problem with your query is that you're based off the database tables named not per Rails convention of having plural table names. I can provide an example similar to yours, it looks like this:
Universe.joins(
galaxies: {
stars: {
planets: {
molecules: :atoms
}
}
}
).where(atoms: {id: 5})
And this query assumes you have models:
Universe
that has_many :galaxies
Galaxy
that has_many :stars
and belongs_to :universe
(as such, has universe_id
)Star
that has_many :planets
and belongs_to :galaxy
Planet
that has_many :molecules
and belongs_to :star
Molecule
that has_many :atoms
and belongs_to :planet
Atom
... just belongs_to :molecule
Upvotes: 1
Reputation: 26972
I would start by reading this: http://guides.rubyonrails.org/association_basics.html and creating tables with names that somehow represent the data you are working with. Create migrations model classes with the proper associations and come back and update your question.
Upvotes: 0