Spree: customize the key attributes of a product
Asked Answered
U

2

6

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.

Unspoken answered 3/5, 2011 at 21:52 Comment(0)
W
9

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.

Wardell answered 19/6, 2011 at 20:0 Comment(0)
K
0

My way to extend Product model for Spree (via delegate_belongs_to):

#app/models/product_decorator.rb
Spree::Product.class_eval do
  has_one :product_extension
  accepts_nested_attributes_for :product_extension, :allow_destroy => true
  delegate_belongs_to :product_extension, :some_field
  attr_accessible :some_field
end

#app/models/product_extension.rb
class ProductExtension < ActiveRecord::Base
  belongs_to :product, :class_name => 'Spree::Product'
  attr_accessible :some_field
end
Kolosick answered 24/10, 2012 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.