2011-05-19 21 views
6

我怎樣才能修改從http://localhost:3000/profiles/1http://localhost:3000/myusername路由?如何在Rails 3中擁有site.com/username而不是site.com/user/1?

我有以下表輪廓模型:

def self.up 
    create_table :profiles do |t| 
     t.string :username 
     t.text :interest 

     t.timestamps 
    end 
end 

而且我的routes.rb文件:

resources :profiles 

我看過處理to_paramdevisenested loop同樣的情形答案或即使an example in Rails 2.3,但我找不到一個有效的方法。

我應該對profile/view/show.html.erb,routes.rb和model/profile.rb(如果有)做出什麼修改來修改從http://localhost:3000/profiles/1http://localhost:3000/username的路由?我從基礎知識中學習,因此我寧願不使用任何寶石或插件。

回答

5

如果你想使用的,而不是ID的用戶名嘗試friendly_id寶石。

如果你想自己做,最簡單的方法是重寫方法to_param在我們的模型中返回的用戶名,然後在你的控制器通過用戶名進行搜索。

在模型:

​​

在控制器:

def show 
    @user = User.find_by_username(params[:id]) 
end 

在的routes.rb文件:

match '/:id' => 'profiles#show' 
+0

@Egor:謝謝!是的,這會有所幫助,我可以使用寶石或甚至設計。但我試圖學習,因此沒有任何寶石從基礎知識做。 – Sayanee 2011-05-19 09:35:06

+1

您可以在我們的模型中覆蓋方法to_param以返回用戶名,然後通過用戶名在您的控制器中進行搜索。 我更新答案的細節。 – Egor 2011-05-19 09:40:34

+0

謝謝葉戈爾!然而,這給了我http:// localhost:3000/profile/username,還沒有,http:// localhost:3000/username。我想,我還需要修改routes.rb? – Sayanee 2011-05-19 09:50:46

相關問題