在我的申请中,我想做到这一点,以便可以管理产品或卖家本身的卖家佣金,所以我的路线看起来像这样:
resources :sellers do
resources :commissions
end
resources :products do
resources :commissions
end
我的网址就像:
/products/:product_id/commissions/:id(.:format)
/sellers/:seller_id/commissions(.:format)
但我怎样才能在我的CommissionsController内知道请求何时来自产品或卖家,以便我可以根据product_id或seller_id设置我的佣金?
感谢您的建议
答案 0 :(得分:4)
resources :sellers, model: 'Seller' do
resources :commissions
end
resources :products, model: 'Products' do
resources :commissions
end
然后在控制器中获取model
和id
,如下所示:
model = params[:model].constantize
id = params[params[:model].foreign_key]
答案 1 :(得分:0)
您只需检查是否存在params[:product_id]
或params[:seller_id]
:
#app/controllers/commissions_controller.rb
class CommissionsController < ApplicationController
before_action :set_model
def index
@commissions = @model.find @id
end
private
def set_model
case true
when params[:seller_id]
model = "Seller"
when params[:product_id]
model = "Product"
end
@model = model.constantize
@id = model
end
end