【发布时间】:2014-01-06 14:23:59
【问题描述】:
例如,我有一个页脚
<%= link_to 'Tweets', tweets_path %>
<%= link_to 'Blogs', blogs_path %>
在推文索引页面中,我想隐藏<%= link_to 'Tweets', tweets_path %>。并展示其他东西。我怎么知道用户当前在resource 上?
具体来说,我想
resources = ['Tweet', 'Blog'] # get the model names, and there maybe something more to be added later
resources.each do |resource|
if controller.controller_name = resource && controller.method_name = 'index'
link_to new_resource_path # for example, link_to new_tweet_path
else
link_to resource_path # for example, link_to tweets_path
end
end
粗略的想法在上面。但是在controller.controller_name和link_to方法中,不知道具体写法。
我从Can I get the name of the current controller in the view? 找到controller.controller_name
有什么好的方法可以做到这一点?
更新:
def footer_helper
resources = ['tweet', 'blog'] # and perhaps something more
resources.each do |resource|
if current_page?(controller: resource.pluralize, action: 'index')
link_to "New #{resource.humanize}", {controller: resource.pluralize, action: 'new'}
else
link_to "#{resource.pluralize.humanize}", {controller: resource.pluralize, action: 'index'}
end
end
end
结束
现在我已经把它变成了像上面这样的助手。但是我觉得.pluralize 和.humanize 很烦人,有什么办法可以摆脱它们吗?
另外,如何在视图中使用它?当我使用<%= footer_helper %> 时,它显示["tweet", "blog"]。它无法正常返回。
【问题讨论】:
标签: ruby-on-rails