【问题标题】:How can I get current_page? to match multiple actions?如何获得 current_page?匹配多个动作?
【发布时间】:2014-02-01 00:54:03
【问题描述】:

我的问题是我正在尝试做类似的事情

current_page?(controller: 'tigers', action:('index'||'new'||'edit'))

当控制器是 Tigers 并且操作是 index、new 或 edit 时返回 true。

上面没有抛出错误,只是匹配第一个动作。

救命!

【问题讨论】:

  • 就我个人而言,我只会写一个方法来逐个检查这些并完成它。跳槽尝试单线检查不值得花时间。
  • 有趣。我仍然比较笨,试图找出做事的最佳方式。感谢您的意见。
  • ruby 很棒,它有时提供的神奇方法有时会令人陶醉,但永远不要忘记,有时仅仅编写代码是解决问题的最佳方法。 ;)

标签: ruby-on-rails haml


【解决方案1】:

更详细,但有效:

current_page?(controller:'bikes') &&
 (current_page?(action:'index') ||
  current_page?(action:'new')   ||
  current_page?(action:'edit'))

不那么冗长,也可以:

params[:controller] == 'bikes' && %w(index new edit).include?(params[:action])

%w() 是构建空格分隔字符串数组的快捷方式

【讨论】:

  • 所有好的答案,我选择了这个,因为它是我一直在寻找的单线。谢谢!
【解决方案2】:

你也可以这样做:

if current_page?(root_path) || current_page?(about_path) || current_page?(contact_path) || current_page?(faq_path) || current_page?(privacy_path)

注意:括号前不要留空格,否则无效。

【讨论】:

  • 使用如上所示的路由助手似乎比列出的其他选项更灵活。 我遇到了一个问题,我的根项目中的模板使用更明确的语法(例如提供操作,散列中的控制器)在共享相同模板的已安装引擎中引起问题。基本上,引擎期望指定的控制器成为引擎的一部分。使用路由路径助手纠正了这种情况!谢谢。
【解决方案3】:

使用 current_page 的替代方法?方法是直接检查params hash:

params[:action] == ('index' || 'new' || 'edit')

如果在 index、new 或 edit 上将返回 true。也可以通过 params[:controller] 访问控制器。

【讨论】:

  • 这似乎对我不起作用,但我可能把它放在了错误的地方。
  • 这行不通。 ('index' || 'new' || 'edit') 基本上等于 'index',因为它是真实的。
  • 你可以改为:[:index, :new, :edit].include? params[:action]
猜你喜欢
  • 2020-11-02
  • 2019-11-13
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
相关资源
最近更新 更多