ruby-on-rails – Rails:不同的控制器行为取决于路由

我正在寻找解决以下情况的最佳做法:

我有一个“添加”模型,它应该是与其他一些模型相关的多对多模型.

例子:

# Meal-Model
has_and_belongs_to_many :additives

# Offer-Model
has_and_belongs_to_many :additives

# Additive-Model
has_and_belongs_to_many :meals
has_and_belongs_to_many :meals

路由以下列方式嵌套:

resources :offers do
  resources :additives
end
resources :meals do
  resources :additives
end

所以我得到这样的网址:

/offers/123/additives
/meals/567/additives

两条路线都导致相同的控制器动作,即添加剂#index.在AdditivesController中,我检查params是否可用于选择要获取的数据:

class AdditivesController < ApplicationController

before_filter :offermealswitch

# GET /restaurants/1/meals/123/additives
# GET /restaurants/1/offers/123/additives
def index   
  @additives = @additivemeal.additives    
end

def offermealswitch
  if params.has_key?(:meal_id)
    @additivemeal = Meal.find(params[:meal_id])
    @type = "Meal"
  elsif params.has_key?(:offer_id)
    @additivemeal = Offer.find(params[:offer_id])
    @type = "Offer"
  end
end

end

这是处理这个问题的正确方法吗?它工作得很好,但我不是shure这是轨道方式……
谢谢你的回答!

最佳答案 叹息切换到应答空间所以我至少可以添加回车并使代码不笨.

我同意fl00r的答案,但会补充说你需要实例化对象:

@type = params[:type] 
@obj = @type.constantize.find(params["#{type}_id"])
@additives = @obj.additives 
点赞