2013-07-28 145 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