[英]Ruby on Rails: If Else based on params[:example]
我有一个控制器订单。 这个控制器根据 POST 请求做不同的事情。 当用户购买产品时,它会进入他的库存。 所以只能销售有库存的产品。 库存表有一个 product_id 列。 简单地说,当用户在 products/product_id 页面上的订单必须是买入,当在 stock/stock_id 页面上的订单必须是卖出。
路线.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 会造成一些损害吗? 例如卷曲。 非常感谢。
是否可以以某种方式在请求中注入参数? 例如将 params[:product_id] 注入 stoks/stock_id/orders 会造成一些损害吗? 例如卷曲
是的。 没有什么能阻止您向/stocks/123/orders?product_id=123
发送请求。 结果params[:product_id]
将出现并且订单将收到错误的类型。
为每种类型的订单创建一个单独的控制器怎么样?
resources :products, only: [:index, :show] do
resources :product_orders, only: [:create]
end
resources :stocks, only: [:index, :show] do
resources :stock_orders, only: [:create]
end
那么ProductOrdersController
将像这样简单:
class ProductOrdersController < ApplicationController
def create
order.type = 'buy'
end
end
然后StockOrdersController
将是这样的:
class StockOrdersController < ApplicationController
def create
order.type = 'sell'
end
end
这将帮助您停止依赖传递的params
并摆脱if
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.