2013-07-28 75 views
0

首先,我是新手到rails
我有一個像這樣的控制器。查詢工作正常。Rails動態路由到控制器的不同實例變量

class StoreController < ApplicationController 

    def men_clothing 
    @men_clothing=Category.find_by_name("clothes").products.where(product_type: "men") 
    @men_clothing_tshirt=Category.find_by_name("clothes").sub_categories.find_by_name("t-shirt").products 
    end 

現在我有一個men_clothing在我能夠顯示所有產品通過遍歷它@men_clothing實例變量視圖。

但在我的主頁我有我想直接到@men_clothing_tshirt實例的鏈接變量,使得點擊該鏈接,將顯示該實例variable.And的所有產品,如果有另一個鏈接應該直接到不同的實例變量。

我該怎麼做到這一點?或者建議一種替代方法來做到這一點。請解釋它是如何工作的。

我知道我可以通過爲每個實例變量分別執行一個操作併爲它創建一個視圖。但在這種情況下,我將不得不提出很多觀點。

回答

1

也許你可以試一試similar to this link

[:tshirt, :pant, :banana_hammock].each do |category| 
    get "mens_#{category}/:id", :controller => :mens, :action => :show, :type => category, :as => "mens_#{category}" 
end 

然後,您將得到您正在查找的路徑,例如, mens_tshirt_pathmens_pant_path

在你的控制,你會改變操作更改基於對傳入的「類型」

class MenController < ApplicationController 
    before_filter :find_clothing_by_category 

    private 

    def find_clothing_by_category 
    @clothing = Clothes.where(category: params[:type].to_s) 
    end 
end 
0

你的鏈接沒有重定向到你的實例,它的重定向到你的動作。所以你必須定義新link_to一種新方法,並定義@men_clothing_tshirt對象該方法是這樣的:

def your_method 
    @men_clothing_tshirt=Category.find_by_name("clothes").sub_categories.find_by_name("t-shirt").products 
end 

,並在您link_to重定向到your_method

link_to "Tshirt", your_method_path 

希望這將有助於。謝謝

+1

正如我所說,我知道這種方法。但事情是,通過這種方法,我將不得不爲所有這樣的實例變量創建方法和視圖,這些變量的數量很大。 – mrudult