Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Expanded Model Decorator guide

Damian Legawiec9ff42905579e
diff --git a/guides/src/content/developer/customization/logic.md b/guides/src/content/developer/customization/logic.md
index 605331888e..cac811bf9f 100644
--- a/guides/src/content/developer/customization/logic.md
+++ b/guides/src/content/developer/customization/logic.md
@@ -28,9 +28,52 @@ Adding a custom method to the [Product](https://github.com/spree/spree/blob/mast
module MyStore
module Spree
module ProductDecorator
+ def self.prepended(base)
+ base.before_validation :strip_whitespaces
+ end
+
def some_method
...
end
+
+ protected
+
+ def strip_whitespaces
+ ...
+ end
+ end
+ end
+end
+
+::Spree::Product.prepend MyStore::Spree::ProductDecorator if ::Spree::Product.included_modules.exclude?(MyStore::Spree::ProductDecorator)
+```
+
+#### Adding new associations to existing models
+
+Assume you want to add a new model called `Video` associated to `Spree::Product`. Let's start with creating a database migration:
+
+```shell
+bundle exec rails g migration CreateVideos url:string product:references
+bundle exec rails db:migrate
+```
+
+Add new model to `app/models/videos.rb`:
+
+```ruby
+class Video < ApplicationRecord
+ belongs_to :product, class_name: 'Spree::Product'
+end
+```
+
+Finally add the association in `ProductDecorator` in `app/models/my_store/spree/product_decorator.rb`:
+
+```ruby
+module MyStore
+ module Spree
+ module ProductDecorator
+ def self.prepended(base)
+ base.has_many :videos, class_name: 'Video', foreign_key: 'product_id', dependent: :destroy
+ end
end
end
end