Search code examples
ruby-on-railsrubyspreetaxonomy

Programmatically generated Spree Taxons not showing tree in Admin


I am trying to generate a Spree Commerce taxonomy programmatically within a Ruby script (a la seeds.rb). In the customer-facing product pages the Taxons appear, but they do not work from the Admin pages.

  • The "tree" view of the Taxonomy shows the root node, but no children
  • On the product edit page, I cannot add any of my Taxons

Here's an example:

taxonomy_stones = Spree::Taxonomy.where(:name => 'Gemstone Type').first_or_create
tax_stones = Spree::Taxon.where(name: "Gemstone", parent: nil, taxonomy: taxonomy_stones).first_or_create
tax_diamond = Spree::Taxon.where(name: "Diamond", parent: tax_stones, taxonomy: taxonomy_stones).first_or_create
  tax_fancy_yellow = Spree::Taxon.where(name: "Fancy Yellow Diamond", parent: tax_diamond, taxonomy: taxonomy_stones).first_or_create
  tax_fancy_pink = Spree::Taxon.where(name: "Fancy Pink Diamond", parent: tax_diamond, taxonomy: taxonomy_stones).first_or_create

When I run this, entries appear in the database for my Taxonomy and Taxons. I am able to programmatically associate Products to the Taxons:

product_BL212.taxons << tax_diamond

I'm guessing that my Taxon-creation code is incomplete or incorrect in some way, but I am not sure how. Can anyone who is more familiar with Spree's internals provide an example of doing this correctly?

Further Observations

I used the Admin UI to create sample Taxonomies and have compared the database entries to my generated ones. The name and permalink fields in spree_taxons are blank for my generated Taxons, but not the Spree-created ones. When I manually populated some of the values for the root node and two sample children, the taxonomy/taxons still don't work correctly in Admin.

Is it important to have these values populated in spree_taxons when spree_taxons_translations has the needed information? If so, how do I get Spree to populate the values for these fields correctly?


Solution

  • Calling Spree::Taxon.rebuild! after adding the Taxons resolves the issue.