On Apr 14, 5:53 pm, Shawn <[email protected]> wrote: > Here's something I'd love to do. I would like to traverse several > associations and select all the matching model objects from the last > model in the chain, without getting the results for the other tables. > No combined results, no graphs, just model objects from the last table > in the join. And I'd like this to happen in just one SQL query. > > modelA_object.assocB_dataset.assocC_dataset.assocD_dataset.all > > #=> > SELECT tableD.* > FROM tableB > JOIN tableC ON (...) > JOIN tableD ON (...) > WHERE tableB.tableA = #{modelA_object.id} > > (modified by any conditions, orders, or other options of the > associations involved) > > This may require making datasets "model-aware," meaning aware of the > model from which they originated, so they can access the model's > associations and other methods. This might be useful in other cases > too; I've found myself wishing that datasets had model-awareness on > more than one occasion.
Model datasets are already model aware, as they have a model method that returns the related model (see http://sequel.rubyforge.org/rdoc/classes/Sequel/Model/DatasetMethods.html), with association datasets also being aware of the related object and the related association reflection (http://sequel.rubyforge.org/rdoc/ classes/Sequel/Model/Associations/AssociationDatasetMethods.html). Note that the many_through_many plugin can handle associations through multiple join tables, though it's up to you to set any conditions, orders, or other options specific to such an association. You can already get something similar with your existing associations using: ModelD.eager_graph(:ModelC=>:ModelB).filter(:ModelB__ModelA_id=>ModelA_object.id).ungraphed.select(:ModelD.*) Note that I started with ModelD instead of ModelB. It doesn't have to be done this way, but it is easier, as otherwise you need to modify the row_proc for the dataset. Jeremy -- You received this message because you are subscribed to the Google Groups "sequel-talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/sequel-talk?hl=en.
