Saturday, January 31, 2009

How to add "Cross Sell" with rails

cross_sell products (Related products):

create table products :

CREATE TABLE products (
id INT NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (id)
);

Create a table 'cross_sell' in the mysql query browser :

CREATE TABLE cross_sells (
product_id INT NOT NULL,
cross_sell_product_id INT NOT NULL,
cs_position INT NOT NULL,
PRIMARY KEY (product_id, cross_sell_product_id),
UNIQUE KEY pos (cs_position)
);

steps to create a table in mysql query browser:

1. Right click on the database and select 'create table'.
2. Fill all the fields, all the columns and say apply. and execute.

In the model say 'product', type the following :
has_and_belongs_to_many :cross_sell_products,
:join_table => 'cross_sells',
:foreign_key => 'product_id',
:association_foreign_key => 'cross_sell_product_id',
:class_name => 'Product',
:order => 'cs_position'

In the show view of product :i.e in our example : /view/home/product.html.erb

Related Products :


<% @product.cross_sell_products.each do |cross_sell_product|%>
<%= link_to cross_sell_product.name, :action => 'product',
:id => cross_sell_product.id %>

<% end %>

Now fill in the table cross_sell, with product_id and its related product id, ie. cross_sell_id.

No comments:

About Me

Friendly and humanitarian Honest and loyal Original and inventive Independent and intellectual