【问题标题】:how to combine different controller name with other controller action? Rails如何将不同的控制器名称与其他控制器动作结合起来?导轨
【发布时间】:2013-06-27 09:17:39
【问题描述】:

我想实现这样的功能。 所以我有产品控制器,它处理产品 CRUD。 而且我还有类别控制器,它处理类别 CRUD。

我想要实现的是,当我在浏览产品展示动作时,在浏览栏我可以看到这样的url

www.mydomainname.com/products/category_name/product_name

此刻我有。

www.mydomainname.com/products/city-skid-7v3

所以这意味着我需要在路由中组合 2 个控制器。有人有示例或建议吗?

【问题讨论】:

    标签: ruby-on-rails url routing


    【解决方案1】:

    你应该在你的routes.rb:

    namespace :products do
      resources :categories do
        resources :products
      end
    
      # to index products without category:
      resources :products, only: :index
    end
    

    那么您应该更改 views/controllers 中您使用路线的所有位置。例如,如果您有

    link_to product.name, product
    

    您应该将其替换为:

    link_to product.name, [:products, product.category, product]
    

    由于现在链接到产品时,您还需要指定类别 url 段。

    在您的products#index 中,您现在可以检查是否提供了category_id 并分别过滤产品:

    scope = if params[:category_id]
      Category.find_by_permalink!(params[:category_id])
    else
      Product
    end
    @products = scope.all # add your other scopes here
    

    【讨论】:

    • 我应该以什么方式更改视图和控制器?对不起,我还在学习。谢谢
    • 你现在的routes.rb怎么样?
    • Darbs::Application.routes.draw do get "about_us/index" root :to => 'home#index' namespace :products do resources :categories do resources :products end end devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) resources :news get "about/index" # get "contacts/index" get "home/index" match "/products/search" => "products#search" get "panel/index" match "/contacts", to: "contacts#index" match "/home", to: "home#index" match "/about_us", to: "about_us#index" match "/news", to: "news#index" resources :manufacturers
    • 此时我无法使用资源:产品路线,那么我如何才能使用产品/索引路径?
    • 你想索引没有分类的产品?
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    相关资源
    最近更新 更多