Rails:根据路由不同的控制器行为

时间:2011-05-10 10:06:14

标签: ruby-on-rails parameters many-to-many params routes

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

我有一个“添加剂”模型,它应该与其他一些模型相关联。

示例:

# 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

两条路线都会导致相同的控制器操作,即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这是轨道方式...... 谢谢你的回答!

2 个答案:

答案 0 :(得分:1)

关于@Taryn East的

编辑

resources :offers do
  resources :additives, :type => "Offer"
end
resources :meals do
  resources :additives, :type => "Meal"
end

class AdditivesController < ApplicationController
  before_filter :find_additive

  def index   
    @additives = @additive.additives    
  end

  private
  def find_additive
    @type = params[:type]
    @additive = @type.constantize.find([@type, "id"].join("_")) # or "#{@type}_id", as you wish
  end
end

答案 1 :(得分:1)

叹息切换到应答空间,这样我至少可以添加回车并使代码不会变得愚蠢。

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

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