使用子路由Rails自定义路由

时间:2015-07-13 17:16:14

标签: ruby-on-rails ruby ruby-on-rails-4 rails-routing

我遇到这个问题,我为比萨店建立了一个网站,我在这个案例中有两个型号ProductCategory和Product。产品属于ProductCategory,其中每个类别都有许多产品。我已经将product_categories_path命名为类别,例如product_categories#index =>类别,但现在我想在路径/product_category.name/中找到产品索引页面的链接,但我的路线远非正确。

Routes.config

FragmentB fragmentB = FragmentB.newInstance();
transaction = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragmentB);

if (lastClicked == Constants.FRAGMENT_B) {
    ((AppCompatActivity) context).getSupportFragmentManager().popBackStack();
}

transaction.addToBackStack("FragmentB");

try {
    transaction.commit();
} catch (IllegalStateException e) {}

lastClicked = Constants.FRAGMENT_B;

product.rb

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_category.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

我应该在products_controller.rb和index-action中执行此操作,我会有类似的内容:

class ProductCategory < ActiveRecord::Base
has_many :products

validates :name, presence: true, length: {in: 3..30}, uniqueness: { case_sensitive: false }
end

非常感谢您的帮助!

0 个答案:

没有答案