Rails Kitchen

It's a place to write on stuff I learned recently.

Spree - Add Extra Fields to Product Model With Deface and Decorator

| Comments

Spree is a fully-featured e-commerce solution that can be easily integrated into a Rails application. If you need to turn a Rails app into a store that sells products then Spree is one of the quickest ways to do this. We can customise all the built-in features in Spree and can also and new features and fields to Spree models.

In this post, I am discussing adding an extra field for the uploading company logo into products. For customising view of product form we can use Deface. To add has_attached_file relation to product model we use decorator.
First we need to create migration for adding company logo field to spree_products table.
1
2
3
4
5
class AddCompanyLogoToSpreeProducts < ActiveRecord::Migration
  def change
    add_attachment :spree_products, :company_logo
  end
end
To add has_attached_file relation to product model, add product decorator to file app/model/spree/product_decorator.rb
1
2
3
4
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 only can add file upload filed to product form using deface.
Deface is a standalone Rails library that enables you to customize Erb templates without needing to directly edit the underlying view file. Deface allows you to use standard CSS3 style selectors to target any element (including Ruby blocks), and perform an action against all the matching elements
Add deface code into app/overrides/company_logo_to_admin_product.rb
1
2
3
4
5
6
7
8
9
10
11
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           => "
          <p>
                <%= f.label :company_logo %>
                <%= f.file_field :company_logo %>
          </p>
"
)
Thats it , now we can start uploading company logo to each product

Comments