2014-10-29 63 views
1

我在Rails 4中有一个电子商务网站,其中产品列表路线基于'资源列表'。这使得列表显示页面路由为/ listing /:id。我想在路线中包含产品名称并将其设置为/ listing /:id /:name - 我将如何执行此操作。更改Rails路线以包含其他模型属性

我看到了友善的宝石,但我宁愿没有宝石就做这个,如果有一个简单的方法。

这里是上市路线区块:

resources :listings do 
     collection do 
      post 'import' 
      get 'search' 
      get 'delete_all' 
     end 
    resources :orders, only: [:new, :create, :update, :show] 
    end 

每豪尔赫的答案下面,我添加了一个get '/:name' => 'listings#show'但是当我做耙路线,我得到一个错误说“找不到没有ID列表”,我仍然查看原始路线/列表/:id指向列表#show。

更新: 当我粘贴上述新路线时,点击产品时的默认路线仍然是/ listings /:id。然而,当我在新的路由/上市/型号:ID /:文件名(如列表/ 324/testlisting)我得到一个错误如下:

Started GET "/listings/324/brand" for 127.0.0.1 at 2014-10-29 12:55:35 -0700 
Processing by ListingsController#show as HTML 
    Parameters: {"listing_id"=>"324", "name"=>"brand"} 
Completed 404 Not Found in 1ms 

ActiveRecord::RecordNotFound (Couldn't find Listing without an ID): 
    app/controllers/listings_controller.rb:189:in `set_listing' 

的“set_listing”的方法只是发现基于上市ID。这里是列表控制器的一部分。

before_action :set_listing, only: [:show, :edit, :update, :destroy] 

    def show 
    end 

    def set_listing 
    @listing = Listing.find(params[:id]) 
    end 
+0

帕拉姆被命名为:listing_id,但你在Listing.find(params [:id])中搜索[:id]。这就是失败的原因。 – tebayoso 2014-10-29 20:14:30

回答

0

这是你在找什么:

Rails3 Routes - Passing parameter to a member route

http://guides.rubyonrails.org/routing.html#nested-resources

resources :listing do 
    get '/:name', to 'listings#whatever' 
end 

编辑:

请问你的路线看起来像这些?

resources :listings do 
    get '/:name', :to => 'listings#show' 
    collection do 
     post 'import' 
     get 'search' 
     get 'delete_all' 
    end 
    resources :orders, only: [:new, :create, :update, :show] 
    end 

编辑2:

我建议创建一个新的方法:

def show_by_name 
    @listing = Listing.find_by(name: params[:name]) 
    render action: 'show' 
end 

而且使用它的路线:

get '/:name', :to => 'listings#show_by_name' 
+0

这给了我一个错误'找不到没有ID的列表' – Moosa 2014-10-29 19:34:20

+0

粘贴正在传递给控制器​​的参数。 – tebayoso 2014-10-29 19:40:02

+0

我不知道如何找到正在传递的内容。我只是更新了我的帖子,包括我的代码块和其他一些细节。 – Moosa 2014-10-29 19:44:17