2016-07-29 76 views
0

我是rails的新用戶,因此瞭解routes.rb的工作方式很複雜!所以我嘗試修改路線,我得到了一個如下所示的路徑: user/:id/edit但我希望該ID不會出現在路徑中。在rails中修改路由

我嘗試使用這種方法:

get '/users/:id/edit', to: 'users#edit', as: 'users/edit' 

但它改變不了什麼。在我的routes.rb我得到了:

resources :users, only: [:create, :new, :show, :edit] 

有人知道如何做到這一點?我已經在this guide

+0

你不希望用戶ID的任何特別的原因當下。如果您擁有衆多的用戶,它會使您的應用程序更具REST風格,並且您可以進行驗證,以便用戶只能編輯自己的帳戶。你是否也可以爲你的routes.rb提供你的代碼。當你說它沒有改變時,你的意思是什麼?您是否遇到特定錯誤或路線保持不變? –

+1

@AlexanderSwann奇異資源非常安靜。 –

+0

啊好的!很高興知道,謝謝! –

回答

0

如果你已經採取,

resources :users 

現在改變這條路線如下,

get '/users/edit', to: 'users#edit', as: 'users_edit' 

現在,在你有edit link你的視圖文件,更改鏈接,

<%= link_to 'Edit', users_edit_path(:id => user.id) %> 

現在這個鏈接,用戶控制器與編輯操作id parameter

現在,在用戶控制文件,

class UsersController < ApplicationController 

    def edit 

    // params[:id] will be the ID that you sent through the view file. 
    @user = User.find(params[:id]) 

    end 

end 

完蛋了,你與你定製的路線進行的,現在的路線將是users/edit instead of users/:id/edit

+0

@maluss,試過了嗎? – Sravan

2

看看如果你已經看一看導遊,你瞭解singular resources?

有時候,你有資源的客戶端總是仰望沒有 引用的ID。例如,您希望/ profile始終顯示當前登錄用戶的配置文件 。 在這種情況下,你可以使用 單一資源/型材(而非/資料/:ID)映射到 表演動作

resource :geocoder 

創建應用程序中的六個不同的路線,所有映射到地理編碼器控制器:

GET   /geocoder/new geocoders#new return an HTML form for creating the geocoder 
POST   /geocoder geocoders#create create the new geocoder 
GET   /geocoder geocoders#show display the one and only geocoder resource 
GET   /geocoder/edit geocoders#edit return an HTML form for editing the geocoder 
PATCH/PUT /geocoder geocoders#update update the one and only geocoder resource 
DELETE  /geocoder geocoders#destroy delete the geocoder resource 
+0

謝謝!我修改我的routes.rb添加資源地理編碼器,並修改我的路線是這樣的:get'/ users',到::show,controller:'users' 但我得到一個錯誤,沒有路由匹配[GET]「/ users/1 /編輯「所以我的程序試圖找到舊的路徑,我該如何改變它? – maluss

+0

@maluss更改'* _path'幫手。 –