Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spree: customize the key attributes of a product

Tags:

spree

Does anyone know if it's possible to add a new attribute to the set of key attributes (Name, Description, Permalink, Meta Description etc) of a product? The idea is that I want to have these attributes available when I create a product instead of adding them afterwards through Product Properties.

Thanks.

like image 252
trivektor Avatar asked May 03 '11 21:05

trivektor


1 Answers

The simplest way would be to add attributes directly to the Product model through migrations. Validations can be added through the use of the decorators, the preferred pattern within Spree for overriding models.

# in app/models/product_decorator.rb
Product.class_eval do
  validates :some_field, :presence => true
end

Another option would be to create a secondary model for your extended fields. Perhaps ProductExtension

# in app/models/product_extension.rb
class ProductExtension < ActiveRecord::Base
  belongs_to :product

  validates :some_field, :presence => true
end

# in app/models/product_decorator.rb
Product.class_eval do
  has_one :product_extension
  accepts_nested_attributes_for :product_extension
  delegate :some_field, :to => :product_extension
end

Then in your product creation forms you can supply these fields with a fields_for. I think one caveat with this is your going to need to have the created Product model before the extension becomes usable. You could probably get around this with some extra logic in the product controllers create action.

like image 157
Cluster Avatar answered Oct 16 '22 04:10

Cluster