2013-11-24 83 views
11

我正在構建一些rails示例應用程序,其中我有兩個模型用戶和項目。兩者之間的關聯是用戶has_many項目。現在的問題是我願意爲用戶的項目提供一些下拉菜單,如果有人點擊那個項目,它會將其用於項目顯示頁面。但是,如果用戶在一個項目的編輯頁面,並從下拉菜單中選擇其他項目,我希望他能夠到達新選定項目的編輯頁面。我正在尋找的解決方案是,例如: - 我們可以使用params [:controller]找到當前控制器,使用params [:action]查找當前操作,我如何找到當前路由。 Thanx提前如何在rails中獲取當前路徑

如果有人想看到的是我的代碼: - 這裏是鏈接github上: - 'https://github.com/peeyushsingla/session_test.git/這裏我使用簡單的鏈接,但實際上我將提供一些單一下拉將要顯示的將所有的編輯,顯示,新的每一個動作

回答

23

工作要檢索的URL:

# Current URL: 
request.original_url 

# Current relative URL: 
request.request_uri 

此外,您可以用current_page方法檢查您是否是在一定的航線。

current_page?(my_path) 
# => true/false 

對於軌道4使用:

# Current URL: 
request.original_url 

# Current relative URL: 
request.fullpath 
+3

'request.request_uri'不適用於我(Rails 4)我必須用user'path'而不是 – jmarceli

+0

謝謝,我更新了答案 –

+0

undefined方法current_page? –

20

對於軌道4

URL例如:http://localhost:3000/allreferred?&referred_name=maria

request.path -> "/allreferred"

request.base_url -> "http://localhost:3000"

request.fullpath -> "/allreferred?&referred_name=maria"

request.original_url -> "http://localhost:3000/allreferred?&referred_name=maria"

+1

Upvote爲實際例子:) –

2

您可以使用url_for

def current_path(params={}) 
    url_for(request.params.merge(params)) 
end 

URL例如http://localhost:3000/posts

current_path -> /posts

current_path(order: asc) -> /posts/?order=asc

相關問題