Ruby on rails 使用子例程的Rails自定义路由
我有一个问题,我正在为一家比萨店建立一个网站,在这里我有两个模型ProductCategory和Product。产品属于一个ProductCategory,其中每个类别都有许多产品。我已经将to product_categories_path命名为categories,例如product_categories#index=>categories,但现在我希望在path/product_categories.name/中有指向产品索引页面的链接,但我的路径远远不正确 Routes.configRuby on rails 使用子例程的Rails自定义路由,ruby-on-rails,ruby,ruby-on-rails-4,rails-routing,Ruby On Rails,Ruby,Ruby On Rails 4,Rails Routing,我有一个问题,我正在为一家比萨店建立一个网站,在这里我有两个模型ProductCategory和Product。产品属于一个ProductCategory,其中每个类别都有许多产品。我已经将to product_categories_path命名为categories,例如product_categories#index=>categories,但现在我希望在path/product_categories.name/中有指向产品索引页面的链接,但我的路径远远不正确 Routes.config R
Rails.application.routes.draw do
resources :campaign_products
resources :opening_hours
resources :delivery_areas
resources :contact_infos
resources :delivery_times
resources :exceptional_opening_hours
resources :news
resources :product_extras
resources :product_sizes
resources :payment_options
resources :product_categories, path: "categories"
resources :products do
get "/product_category.name", to: "products#index", as: :products_path
end
resources :pages
get "/menu", to: "product_categories#index", as: :menu
root 'pages#index'
product.rb
class Product < ActiveRecord::Base
belongs_to :product_category
validates :name, presence: true, length: { in: 3..30 }, uniqueness: true
validates :description, presence: true, length: { in: 4..300 }
validates :product_category, presence: true
validates_numericality_of :normal_price, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 999.99
validates_numericality_of :lunch_price, allow_nil: true, :greater_than => 0, :less_than_or_equal_to => 999.99
validates_numericality_of :plus_size_price, allow_nil: true, :greater_than => 0, :less_than_or_equal_to => 999.99
end
class ProductCategory < ActiveRecord::Base
has_many :products
validates :name, presence: true, length: {in: 3..30}, uniqueness: { case_sensitive: false }
end
谢谢你的帮助 我会对主列表执行
category/:name
,对单个产品执行category/{name}/:product\u id
。您可以在模型中将重写为_param
,以便URL帮助程序使用名称而不是id。我将对主列表执行category/:name
,对单个产品执行category/{name}/:product_id
。您可以在模型中将重写为_param
,以便URL帮助程序使用名称而不是id。
def index
@products = Product.all.where(:product_category_id == 1)
end