【发布时间】:2017-10-29 03:48:10
【问题描述】:
我有一个控制器订单。该控制器根据 POST 请求执行不同的操作。 当用户购买产品时,它会进入他的库存。所以只能销售库存产品。 Stock 表有一个 product_id 列。简单来说,当用户在 products/product_id 页面上时,订单必须是买入,而在股票/stock_id 页面上时,订单必须是卖出。
Routes.rb:
resources :products, only: [:index, :show] do
resources :orders, only: [:create]
end
resources :stocks, only: [:index, :show] do
resources :orders, only: [:create]
end
耙子路线:
products_orders POST /products/:product_id/orders(.:format) orders#create
products_index GET /products(.:format) products#index
product GET /products/:id(.:format) products#show
stocks_orders POST /stocks/:stock_id/orders(.:format) orders#create
stocks_index GET /stocks(.:format) stocks#index
stock GET /stock/:id(.:format) stocks#show
我的模特:
class Order < ApplicationRecord
belongs_to :product
end
class Product < ApplicationRecord
has_many :orders
has_many :stocks
end
class Stock < ApplicationRecord
belongs_to :product
end
所以我这样做了:
class OrdersController < ApplicationController
def create
if params[:product_id].present?
order.type = 'buy'
elsif params[:stock_id].present?
order.type = 'sell'
end
end
end
这段代码安全吗?有没有办法做得更好? 根据 params[:product_id] 和 params[:stock_id] 使用此代码是否正确?
if params[:product_id].present?
order.type = 'buy'
elsif params[:stock_id].present?
order.type = 'sell'
end
是否可以通过某种方式在请求中注入参数? 例如,将 params[:product_id] 注入到 stoks/stock_id/orders 会造成一些损害吗?例如卷曲。 非常感谢。
【问题讨论】:
标签: ruby-on-rails ruby database model-view-controller