5

I'm using Spree in a Rails 3.2 app of mine and I want to extend Spree's Product class to better suit my needs as for example to establish a relationship with another model in my app. What's the best way to do this? I could not find anything about it in the project documentation

And what if I want to add new attributes/fields to the Product resource? I can't find it's migration either :/

Thanks in advance :)

rodrigoalvesvieira
  • 7,895
  • 15
  • 63
  • 84

1 Answers1

19

The best thing to do here is to create a product_decorator.rb in your app.

This will look like the following:

Spree::Product.class_eval do
  ...
end

In there, you can feel free to modify whatever you want!

Here's the documentation for that.

To add a new field to an already existing Model, run a migration like this:

# migration
class AddSubscribableFieldToVariants < ActiveRecord::Migration
  def change
    add_column :spree_variants, :subscribable, :boolean, default: false
  end
end

And then in the model add following:

# spree/variants_decorator.rb
Spree::Variant.class_eval do
  attr_accessible :subscribable
end
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Martin Lang
  • 831
  • 11
  • 20
  • 1
    Thanks. But what if I want to add new attributes/fields to the Product resource? I can't find it's migration either :/ – rodrigoalvesvieira Jan 07 '13 at 20:01
  • 1
    Very easy - Just make a new migration via ("AddNewThingToSpreeProducts thing") and then just add a new attr_accessor line to the decorator. – Martin Lang Jan 07 '13 at 20:03
  • I want to add a new method to this [_model_](https://github.com/spree/spree/blob/v2.4.3/core/app/models/spree/stock/prioritizer.rb#L38-L40), what should be my file name ? [Extending Classes](https://guides.spreecommerce.com/developer/logic.html#extending-classes) didn't mention about nested models. – Arup Rakshit Feb 06 '15 at 11:59
  • When I add a decorator for a model, the methods from `Spree::Base` are no longer available. I am trying to customize `Spree::Product` which inherits from `Spree::Base`. Has anyone has faced this problem? – Saurabh Mar 15 '16 at 06:35