2011-02-11 38 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