Mr McDonald
Mr McDonald

Reputation: 483

Rail: two models for one table

When a User buys a product, it goes to his stock. So only products in stock can be sold. Stock table has a product_id column. Simply, when a user is on products/product_id page orders must be a buy, when is on stocks/stock_id page order must be sell.

I want to use just one table Order, and not to create two table buy_order and sell_order.

So I created buy_order and sell_order model without migration obviously that inherit from Order model, and controllers sell_orders and buy_orders.

I just want to know if this is a correct way to go to use just one table.

My Models:

class Order < ApplicationRecord
    belongs_to :product
end

class BuyOrder < Order
end

class SellOrder < Order
end

class Product < ApplicationRecord
    has_many :buy_orders
    has_many :sell_orders
    has_many :stocks
end

class Stock < ApplicationRecord
    belongs_to :product
end

My Controllers

class BuyOrdersController < ApplicationController

    def create
       ...
       order.type = 'buy'
       ...
    end
end

class SellOrdersController < ApplicationController

    def create
       ...
       order.type = 'sell'
       ...
    end
end

Routes.rb:

resources :products, only: [:index, :show] do
  resources :buy_orders, only: [:create]
end

resources :stocks, only: [:index, :show] do
  resources :sell_orders, only: [:create]
end

Rake Routes:

products_orders POST       /products/:product_id/buy_orders(.:format) orders#create
products_index GET        /products(.:format) products#index
product GET        /products/:id(.:format) products#show
stocks_orders POST       /stocks/:stock_id/sell_orders(.:format) orders#create
stocks_index GET        /stocks(.:format) stocks#index
stock GET        /stock/:id(.:format) stocks#show

Upvotes: 1

Views: 409

Answers (1)

Cyzanfar
Cyzanfar

Reputation: 7136

I can't see the use of separating your "order" model into two distinct one. Personally, I'd chose to go for simplicity. In your order table have an attribute side that will be either sell or buy. A product would then have many orders, each of them belonging to a product.

class Product < ApplicationRecord
    has_many :orders
    has_many :stocks
end

You can then easily refer to the side like:

Product.first.orders.where(side: 'sell')

Would retrieve all sell orders for the first product record.

Upvotes: 1

Related Questions