简体   繁体   中英

Rails dynamic routing to different instance variables of controller

First of all I'm newbie to rails
I have a controller like this one. The queries are working fine.

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  

Now I have a view for men_clothing in which I'm able to show all the products in @men_clothing instance variable by iterating over it.

But in my home page I have a links which I want to direct to @men_clothing_tshirt instance variable such that clicking on that link will show all the products of this instance variable.And if there is another link it should direct to a different instance variable.

How should I achieve this? Or suggest a alternative way to do this. Do explain how it works.

I know I can do that by making separate actions for each instance variable and making a view for it. But in that case I will have to make a lot of views.

Maybe you could try something 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

Then you'll get your paths that you're looking for, eg mens_tshirt_path , mens_pant_path , etc.

In your controller, you would change the action to change based on the incoming 'type'

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

your link is not redirecting to your instance, its redirecting to your action. so you have to define a new method for new link_to that, and define your @men_clothing_tshirt object in that method like this:

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

and in your link_to redirect to your_method :

link_to "Tshirt", your_method_path

Hope it will help.Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM