Rails Routing with Query String

前端 未结 2 582
星月不相逢
星月不相逢 2020-12-18 01:49

I have a problem where I need values passed in from a GET request and I don\'t know how to set up the routing definition.

My Category object has a type(string),a col

2条回答
  •  悲哀的现实
    2020-12-18 02:13

    One RESTful way to to do this would involve a product resource nested beneath a category resource, like so:

    http://www.myapp.com/categories/toy/products?color=red

    Your routes.rb would need to contain:

      map.resources :categories do |category|
        category.resources :products
      end
    

    Since my url above using the Category's type attribute for routing, I'm implying that each type is unique, like an id. It'll mean that whenever you're loading a category in the Categories controller (or anywhere else) you'll need to load the category with Category.find_by_type(params[:id]) instead of Category.find(params[:id]). I like routing categories this way whenever possible.

    Your ProductsController controller index action would find products using lines like:

      @category = Category.find_by_type(params[:category_id])
      @products = @category.products.find(:all, :conditions => { :color => params[:color]} ) 
    

    Remember, your Category model must contain the line:

    has_many :products
    

    It's probable a good idea to enforce that in the model with validations:

    validates_presence_of :type
    validates_uniqueness_of :type
    

    To make routing work you should also overwrite the to_param method in the Category model to return type instead of id:

    def to_param
      self.type
    end
    

提交回复
热议问题