2011-05-10 52 views
4

我在寻找解决以下情况最好的做法不同的控制器行为:的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 

两种途径都导致同一控制器行动,这是additives#index。在添加剂控制器中,我检查是否有参数可供选择要提取哪些数据:

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 

这是处理该问题的正确方法吗?它工作得很好,但我不舒服这是轨道的方式... 感谢您的答案!

+0

我认为您的解决方案是相当不错,直到你的'offermealswitch'是不是太复杂。但是你也可以通过'type'与你的路线 – fl00r 2011-05-10 10:45:05

+0

好的,我发现了一种方法来保存甚至'@type'实例变量:当我需要知道在我的控制器或视图中实际处理了哪种类型时,我检查'@meal .class == Meal'或'@meal.class == Offer'。只要它那么简单,对我来说这似乎是一个很好的解决方案。 – 2011-05-10 11:54:41

回答

1

叹息切换接听空间,所以我至少可以加回车和使代码不是哑巴。

我同意fl00r的答案,但想补充一点,你需要这样来实例化对象:

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

我被认为只是在jeneral,所以我错过了该代码是不工作:) – fl00r 2011-05-10 11:21:59

+0

那总是发生在我身上:) – 2011-05-10 11:27:26

+0

jeneral =一般agrrr – fl00r 2011-05-10 11:29:43

1

编辑相对于@Taryn东

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 
+0

这将需要: @type = params [:type] .constantize; @obj = @ type.find(params [“#{type} _id”]); @additives = @ obj.additives – 2011-05-10 11:12:31

+1

@Taryn East,你可以看到作者需要这个'@type'作为一个字符串,所以我们不能对它进行常量化,或者我们需要将它作为一个字符串返回。但这其实并不重要。是的,你是对的我的错误:) – fl00r 2011-05-10 11:14:01

+0

已经添加并更新了我自己的“答案”(所以格式不吸如坏) – 2011-05-10 11:17:26