2014-10-29 50 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

相關問題