closure_tree icon indicating copy to clipboard operation
closure_tree copied to clipboard

Calling hash_tree to get a subset of model data

Open peterwake opened this issue 7 years ago • 1 comments

With an example model DirectoryEntry, at the moment I can call directory_entry.hash_tree which runs the following query:

SELECT `directory_entries`.*
FROM `directory_entries`
INNER JOIN `directory_entry_hierarchies` ON `directory_entries`.`id` = `directory_entry_hierarchies`.`descendant_id`
WHERE `directory_entry_hierarchies`.`ancestor_id` = 2
ORDER BY `directory_entry_hierarchies`.generations ASC

What I would like to do is just draw a tree, and all I need for this is the id and name of the directory entries, (and probably parent_id to build the ). But I can't work out how to do get a select scope to work. Any suggestions? The query I'd expect to see would be something like:

SELECT 
  `directory_entries`.`id`,
  `directory_entries`.`name`,
  `directory_entries`.`parent_id`
FROM `directory_entries`
INNER JOIN `directory_entry_hierarchies` ON `directory_entries`.`id` = `directory_entry_hierarchies`.`descendant_id`
WHERE `directory_entry_hierarchies`.`ancestor_id` = 2
ORDER BY `directory_entry_hierarchies`.generations ASC

Thanks

peterwake avatar Sep 24 '18 07:09 peterwake

For my use I only needed names for a test to make sure the correct hierarchy was being generated. All I personally needed was the following, so I'm providing it here in case others run into the same situation:

Tag.hash_tree.deep_transform_keys(&:to_s)

You could provide a block to deep_transform_keys if you wanted something else, however this won't help if you actually care about the SQL query generated.

gerrywastaken avatar Dec 06 '18 04:12 gerrywastaken