Ruby on Rails:如果Else基于params [:example]

时间:2017-10-29 03:48:10

标签: ruby-on-rails ruby database model-view-controller

我有一个控制器订单。该控制器根据POST请求执行不同的操作。 当用户购买产品时,它会转到他的库存。因此,只有库存产品才能销售。库存表有一个product_id列。简单来说,当用户在产品/ 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

Rake Routes:

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吗? 例如将params [:product_id]注入stoks / stock_id / orders会造成一些损害吗?例如卷曲。 非常感谢你。

1 个答案:

答案 0 :(得分:0)

  

有可能以某种方式在请求中注入params吗?例如将params [:product_id]注入stoks / stock_id / orders会造成一些损害吗?例如curl

是。没有什么能阻止您向/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声明。