当用户购买产品时,产品会进入他的库存。所以只能销售有库存的产品。 Stock 表有一个 product_id 列。简单地说,当用户在 products/product_id 页面时,订单必须是买入,当用户在 stocks/stock_id 页面时,订单必须是卖出。
我只想使用一个表 Order,而不是创建两个表 buy_order 和 sell_order。
所以我创建了 buy_order 和 sell_order 模型,显然没有迁移,它们继承自 Order 模型,以及 Controller sell_orders 和 buy_orders。
我只想知道这是否是只使用一张表的正确方法。
我的模型:
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
我的 Controller
class BuyOrdersController < ApplicationController
def create
...
order.type = 'buy'
...
end
end
class SellOrdersController < ApplicationController
def create
...
order.type = 'sell'
...
end
end
路线.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 路线:
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
最佳答案
我看不到将您的“订单”模型分成两个不同的模型的用途。就个人而言,我选择简单。在您的订单表中有一个属性 side
,它将是 sell
或 buy
。一个产品
会有很多订单
,每个订单都属于一个产品
。
class Product < ApplicationRecord
has_many :orders
has_many :stocks
end
然后你可以很容易地引用这边:
Product.first.orders.where(side: 'sell')
将检索第一条产品记录的所有销售
订单。
关于ruby-on-rails - rails : two models for one table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027962/