I have a database where Notebooks and Notes have a many_to_many relationship and Notes and Facts have a many_to_many relationship. How do I query the Facts associated with a given Notebook (indirectly associated via a Note) using Ruby Sequel. Should I create another many_to_many relationship between Notebooks and Facts instead? Would that be faster?
Asked
Active
Viewed 1,430 times
1
-
You could use has_many :facts, through: :notes in your notebook controller. the it would be notebook.facts to get the relationship object. Alternative is Notebooks.joins(:notes).joins(:facts).where(your query) which will return a collection of Notebooks. – engineersmnky Mar 22 '14 at 23:29
-
[http://stackoverflow.com/questions/8557835/ruby-on-rails-how-to-join-two-tables][1] [1]: http://stackoverflow.com/questions/8557835/ruby-on-rails-how-to-join-two-tables – J.S. Orris Mar 22 '14 at 23:45
1 Answers
6
Sequel ships with a many_through_many plugin that allows for querying between models through multiple join tables:
Notebook.plugin :many_through_many
Notebook.many_through_many :facts,
:through=>[
[:notebooks_notes, :notebook_id, :note_id],
[:notes, :id, :id],
[:facts_notes, :note_id, :fact_id]
]
n = Notebook.first
n.facts

Jeremy Evans
- 11,959
- 27
- 26