Rick Jones
Rick Jones

Reputation: 56

Adding items to cart with different product types

Hi developers. I am having problem adding items to cart. From rails agile book. If I want to add to products which has different attributes (Apartments, Cars)

class Products
  has_many :line_items
  attributes :name, :price, :content
end

class LineItem
  belongs_to :products
  belongs_to :carts
end

class Cart
  has_many :line_items
end

class Car
  attributes :name, :car_type, :color
end

class Apartment
  attributes :name, :size, :location
end

class Order
  attr :buyer_details, :pay_type
end

Customer adds products to the cart and e.x. 2 bedroom for rent, and limo to rent and wants to pay. How to add to cart. If I put apartment_id and car_id to the lineitems, will it polluted? Please I need correct approach, right practice. Thanks for all.

Upvotes: 1

Views: 909

Answers (1)

TomDunning
TomDunning

Reputation: 4877

Look up polymorphic associations if you definitely want to keep it all in the LineItems. Then make LineItems a poly for products, apartment and car. But I think you're design is really bad here. Buying and renting are very different. With renting you will have a duration, a single address or registration which must not be double booked. Go back and work on your ERD.

One option of better design:

NB i've changed LineItem to be CartItem for clarity.

class Products
  has_many :cart_items
  has_many :order_items
  attributes :name, :price, :content
end


class Cart
  has_many :line_items
end
class CartItem
  belongs_to :products
  belongs_to :carts
end
class CartRental
  # :cart_rentable_type, :cart_rentable_id would be the fields for the polymorphic part
  belongs_to :cart_rentable, :polymorphic => true
  belongs_to :carts
  attributes :from, :till
end

class Order
  attr :buyer_details, :pay_type
end
class OrderItem
  belongs_to :products
  belongs_to :order
end
class Rental
  belongs_to :rentable, :polymorphic => true
  belongs_to :order
   # :rentable_type, :rentable_id would be the fields for the polymorphic part
  attributes :from, :till, :status
end


class Car
  attributes :name, :car_type, :color
  has_many :cart_rentals, :as => :cart_rentable
  has_many :rentals, :as => :rentable
end
class Apartment
  attributes :name, :size, :location
  has_many :cart_rentals, :as => :cart_rentable
  has_many :rentals, :as => :rentable
end

Upvotes: 1

Related Questions