我有一个辅助方法,根据用户所在的当前页面设计生成一个特定路径的链接。基本上,站点范围内的链接应该指向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
我实际上需要链接才能在页面上工作,想到排序链接。它是一个奇怪的问题,很难描述,但我想我可能已经找到了我的解决方案,请参阅编辑。 – noazark 2011-02-11 02:31:23