2011-05-10 53 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