
How to customize Taxon Images in Spree 3.7?
Recently we have migrated from Spree 2.3 to Spree 3.7. We faced many challenges as a lot has been changed in v3.7 compared to v2.3. Below are a few notable changes
- The new style of extending or customizing the model using
module.prepend
. Earlier it was being done usingclass_eval
- Added support of Active Storage. However, Paperclip support is still available but will be deprecated in the next version (Spree 4.0).
- Factory Girl became Factory Bot
- Removed image specific columns from
Taxons
table
We are going to discuss point 4, how to customize the icon or other images for the Taxons.
By default, spree provides an icon for the taxon. Our app needed a page header image for the taxon. If a user visits the specific taxon, let’s say clothing, then he should see the clothing image in the header. So in our case, there were two attachments for the taxon.
- Icon
- Header Image
In Spree 2.3, there were columns of icons in the Taxon table itself. And the declaration was present in the model like below:

Now we need a header image for the taxons as well. So here is the code snippet in taxon_decorator.rb to support the header image.

Below are the columns for the header image which paperclip uses to manage the attachments.

Read Also: Spree 3.6 with Rails 5.2, Ruby 2.5, Active Storage and Multi Store Support!
Now, let’s see how it has been changed in Spree 3.7!
Spree 3.7 started using Single Table Inheritance(STI) and Polymorphism for various models. Storing images for the different models is the classic case for STI associations. For each attachment, there is a separate model file which would be inherited from Spree::Asset
class.
Spree::Assets
is a table which stores all attachments with column type
and two more columns viewable_type
and viewable_id
Here, type column
represents STI and viewable_type, viewable_id
represents the polymorphic association.
We have made below changes to add a header image to the taxon.
Add below relationship in taxon_decorator.rb
has_one :header_image, as: :viewable, dependent: :destroy, class_name: 'Spree::TaxonHeaderImage'
Now, create taxon_header_image.rb
in models/spree directory and use below code
At this point, you may have questions about how to add styles for this attachment!!
For this create paperclip.rb in models/spree/taxon_header_image/configuration
directory and add below code
If you check the entries in Spree::Assets
the table you would see that, type
is Spree::TaxonHeaderImage
and viewable_type
is Spree::Taxon
and viewable_id
is taxon_id
That’s it. This is how Spree 3.7 has decoupled attachments functionality in a modular way.
Click here for more details…
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
We also specialize in Python, RPA, AI, Django, JavaScript and ReactJS.
Consulting is free – let us help you grow!
