2011-02-11 87 views
0

我有一個輔助方法,根據用戶所在的當前頁面設計生成一個特定路徑的鏈接。基本上,站點範圍內的鏈接應該指向items_path,除非用戶在用戶頁面上。所以,我試圖找出一些乾的邏輯,但我一直運行到麻煩:Rails link_to_if問題

def items_link(title, options = {}, html_options = {}) 
    path = request.path 

    case path 
    when users_path,items_path 
    options = request.parameters.merge(options) 
    end 

    link_to_if(path == users_path, title, users_path(options), html_options) do 
    link_to(title, items_path(options), html_options) 
    end 
end 

有了這個解決方案items_path拋出一個No route matches錯誤,儘管路徑是正確的。 users_path工作正常,直到我用link_to切換到link_to_if路徑。

link_to_if(path == items_path, title, items_path(options), html_options) do 
    link_to(title, users_path(options), html_options) 
end 

所以我猜我的問題是在link_to_if的某處。我關門了嗎?我目前的工作解決方案是:

def items_link(title, options = {}, html_options = {}) 
path = request.path 

case path 
when users_path 
    options = request.parameters.merge(options) 
    link_to(title, users_path(options), html_options) 
when items_path 
    options = request.parameters.merge(options) 
    link_to(title, items_path(options), html_options) 
else 
    link_to(title, users_path(options), html_options) 
end 
end 

這工作正常,它只是醜陋。

更新:

我花了更多的時間和算了一下,打破它多一點,這實際上幫助我在另一個領域,我喜歡具有link_action幫手。

def items_link(title, options = {}, html_options = {}) 
    link_to(title, items_link_action(options), html_options) 
    end 

    def items_link_action(options = {}) 
    path = request.path 

    case path 
    when users_path,items_path 
     options = request.parameters.merge(options) 
    end 

    if path == users_path 
     users_path(options) 
    else 
     items_path(options) 
    end 
    end 

回答

0

這是接近我,工作得很好,我認爲。

def items_link(title, options = {}, html_options = {}) 
    link_to(title, items_link_action(options), html_options) 
end 

def items_link_action(options = {}) 
    path = request.path 

    case path 
    when users_path,items_path 
    options = request.parameters.merge(options) 
    end 

    if path == users_path 
    users_path(options) 
    else 
    items_path(options) 
    end 
end 
0

是否有意義將相同的選項放入任一鏈接?這可能是您的No Route Matches錯誤的來源。

我會看current_page?助手和link_to_unless_current助手。

像這樣的東西會顯示一個鏈接到用戶索引操作,除非他們已經在用戶索引操作。項目頁面也可以做同樣的事情。不知道這是不是你想要的。如果是我,我會把剛落,我的佈局兩條鏈路或共享部分:

<%= link_to_unless_current "Users", users_path %> 
<%= link_to_unless_current "Items", items_path %> 
+0

我實際上需要鏈接才能在頁面上工作,想到排序鏈接。它是一個奇怪的問題,很難描述,但我想我可能已經找到了我的解決方案,請參閱編輯。 – noazark 2011-02-11 02:31:23