【问题标题】:route for showing the category name in the url在 url 中显示类别名称的路线
【发布时间】:2012-09-10 13:50:19
【问题描述】:

我是 Rails 开发的新手。我需要有关我必须在应用程序中编写的路线的帮助。我有以下模型:类别、ItemTypes 和 Items。 一个类别可以有多个 itemtype,而 itemtype 又可以有多个 item。

我需要写类似这样的路由:

www.domain.com
-主屏幕。在主屏幕中,我将显示类别列表

当一个类别被点击时,我应该显示属于该类别的所有项目 即,该类别和 url 的所有 itemtypes 的项目应该像

www.domain.com/category-name

项目列表页面将有项目类型的下拉列表。当用户选择项目类型时,用户可以从中过滤项目,网址应该是这样的

www.domain.com/category-name/item-type-name/items

请帮助我为这些案例编写路线。顺便说一句,以下是我编写的模型

   class Category < ActiveRecord::Base
     has_many :item_types
     has_many :items, :through => :item_types, :source => :category

     attr_accessible :name, :enabled, :icon
   end

  class ItemType < ActiveRecord::Base
        belongs_to :category
        has_many :items
  end
  class Item < ActiveRecord::Base
        belongs_to:item_type
  end

提前致谢

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    首先,在 routes.rb 中:

    # Run rake routes after modifying to see the names of the routes that are generated.
    resources :categories, :path => "/", :only => [:index, :show] do
      resources :item_types, :path => "/", :only => [:index, :show] do
        resources :items, :path => "/", :only => [:index, :show, :new]
      end
    end
    

    然后,在您的 category.rb 模型中:

    def to_param # Note that this will override the [:id] parameter in routes.rb.
      name
    end
    

    在您的 categories_controller.rb 中:

    def show
      Category.find_by_name(params[:id]) # to_param passes the name as params[:id]
    end
    

    在您的 item_type.rb 模型中:

    def to_param # Note that this will override the [:id] parameter in routes.rb.
      name
    end
    

    在您的 item_types_controller.rb 中:

    def show
      ItemType.find_by_name(params[:id]) # to_param passes the name as params[:id]
    end
    

    我建议向您的模型添加 before_saves 和验证,以确保名称是 HTML 安全的,类似于 name = name.downcase.gsub(" ", "-")s 的内容应该让您开始使用 before_save(但它绝不是全面的)。

    【讨论】:

    • 感谢@niiru 的快速回复。我的回答与您在回答中所说的完全一样。生成的网址类似于 domain.com/categories/Entertainment... domain.com/categories/Entertainment /item_types/Events...我想从 url 中删除类别和 item_types...我只希望它们如下所示 domain.com/Entertainment.....domain.com/Entertainment/Events..跨度>
    • 资源声明中的:path =&gt; "/" 选项应从您的路线中删除“categories”、“item_types”。我最初将它包含在 :categories 行中,但在 :item_types 和 :items 行中忘记了它。
    • 再次感谢@niiru ..这就像一个魅力..我可以在这些路线上包括这些资源的限制吗:categories,:path =>“/”,:only => [:show ,:index] 做资源 :business_types,:path => "/", :only => [:show, :index] 做资源 :businesses,:path => "/", :only => [:show, : index, :new] end end
    • 是的,这行得通。我也将它添加到答案中。请注意,如果您有 :new,您可能还希望在其中有 :create。
    猜你喜欢
    • 2019-12-23
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2015-01-01
    • 2018-10-15
    • 2015-12-07
    相关资源
    最近更新 更多