ordering through an has_many relationship with a condition in rails 3 / active records / postgresql -
i have 2 objects, items , taxonomy nodes.
i have selection of "items" want order based on alphabetical order of taxonomy_nodes attached to, 1 particular "top parent", id provided (as in "i want sort alphabetically using parent"). if understood nested sets properly, can find out if taxonomy_node belongs parent when left , right values "within" left , right values of top parent: instance top node "vegetable" of values left:1 , right: 10 has "potato" of values left: 2 , right: 8 child.
an item can have several taxonomy_nodes, , using awesome_nested_set gem taxonomy_nodes behave nested sets hierarchy. thus, can have various main "taxonomies" against items tagged, identified "top node".
the way, moment, identify if taxonomy_node belongs particular "top node" use lft , rght values of taxonomy_node, , hit stumbling block when trying allow users sort list of items 1 of main taxonomies.
i imagine way achieve allowed use "conditions" applied in ordering itself, cannot how possible!
ordering more simple field, "item_template", achieved:
@items.joins(:item_template).includes(:item_template}.order("template_name #{sorting_direction}")
here taxonomy table:
table name: taxonomies id :integer not null, primary key name :string(255) parent_id :integer lft :integer rgt :integer created_at :datetime not null updated_at :datetime not null depth :integer
the taxonomies related items through itemtaxonomy object. not overly familiar postgresql, , wondering if maybe write function try , achieve result?
hope clear!
new version after update.
can join items taxonomies , taxonomies must lie within range of "top parent" - can implemented join
. expression in where
clause well.
assuming nested set model per updated description, lft
& right
within range of superior node.
also assuming:
- items without link qualifying taxonomy dropped result
- items multiple links qualifying taxonomies listed multiple times.
select t.name, i.* item join taxonomy_node tn on tn.item_id = i.id -- assuming, no specification join taxonomies t on t.id = tn.taxonomy_id -- assuming ... join taxonomies parent on parent.lft <= t.lft , parent.rght >= t.rght parent.id = ? -- id of "top parent" here order t.name
Comments
Post a Comment