Skip to content

Allowing customers to add products to cart

Valentin Ballestrino edited this page Jan 26, 2016 · 1 revision

One of the ideas behind stall, is that you, as the store developer, should be totally free to build your products structure and plug it to the cart system easily.

So all you have to do is create your Rails models and display them the way you want, and make them sellable by including the Stall::Sellable mixin :

class Book < ActiveRecord::Base
  include Stall::Sellable
end

Then in your templates, use the add_to_cart_form_for helper :

= add_to_cart_form_for(@book)

Your model needs to or can define the following methods (active record attributes are methods !) to customize its behavior when added to the cart :

Method name Required Role Default
#name or #title Yes allows naming the sold product in the cart None
#price Yes the price of the product None
#eot_price No the price without the VAT applied The #price value minus the VAT
#vat_rate No The percentage of VAT in the product The default VAT rate defined in the config initializer

How it works

When added to the cart, the product model instance is fetched and the #to_line_item method is called on the product. This method is defined by the Stall::Sellable module, and creates a Stall::LineItem instance with the needed data.

Note : When you update your product model(s), the line items created from that model won't be updated. This is to ensure that orders are valid even years after they were created.

Customizing line items creation

Since the #to_line_item method is in the Stall::Sellable module, you can override it in your product class as long as you return a valid Stall::LineItem instance that can be saved :

class Book < ActiveRecord::Base
  include Stall::Sellable

  def to_line_item
    line_items.build(
      name: 'My book',
      unit_eot_price: 10,
      unit_price: 12,
      vat_rate: 20
    )
  end
end