- Published on
- • 2 min read
Spree - Add extra fields to product model with deface and decorator
- Authors

- Name
- Shaiju Edakulangara
- @eshaiju
Spree is a fully-featured e-commerce solution that can be easily integrated into a Rails application. You can customize all the built-in features in Spree and add new features and fields to Spree models.
In this post, I am discussing adding an extra field for uploading a company logo to products. To customize the product form view, we can use Deface. To add the has_attached_file relation to the product model, we use a decorator.
First, create a migration for adding the company logo field to the spree_products table:
class AddCompanyLogoToSpreeProducts < ActiveRecord::Migration
def change
add_attachment :spree_products, :company_logo
end
end
To add the has_attached_file relation, create a product decorator in app/models/spree/product_decorator.rb:
Spree::Product.class_eval do
has_attached_file :company_logo,
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "/images/:style/missing.png"
validates_attachment_content_type :company_logo, :content_type => /\Aimage\/.*\Z/
end
Now we can add the file upload field to the product form using Deface. Deface is a Rails library that enables you to customize Erb templates without needing to directly edit the underlying view file.
Add the Deface code into app/overrides/company_logo_to_admin_product.rb:
Deface::Override.new(
:virtual_path => "spree/admin/products/_form",
:name => "company_logo_to_admin_product",
:insert_bottom => "[data-hook='admin_product_form_additional_fields']",
:text => "<%= f.label :company_logo %> <%= f.file_field :company_logo %>"
)
That's it! Now we can start uploading a company logo to each product.