【发布时间】:2014-05-23 15:06:20
【问题描述】:
在 Rails 中有很多次我希望能够将属性添加到某些东西只有当属性具有特定值时。
让我举个例子。假设我想禁用基于特定属性的按钮,例如check_if_user_can_be_added:
link_to 'Create account', new_user_path, disabled: (user_can_be_added?)
这一切看起来都很好,除了 disabled 碰巧在 HTML 中应用,不管你给它什么值。如果你给一个按钮属性disabled: false,那么它仍然会被禁用。
我需要什么
# if the button is disabled
link_to 'Create account', new_user_path, disabled: true
# if the button is not disabled
link_to 'Create account', new_user_path
我能想到的方法
得到这个意味着您需要一个类似于以下的解决方案,它首先设置选项哈希,然后将其传递:
options = user_can_be_added? ? {disabled: true} : {}
link_to 'Create account', new_user_path, options
我想这样做的方式......
这不起作用,但相信 Ruby 的美丽,我怀疑那里有类似的东西。这基本上就是我想做的事情
link_to 'Create account', new_user_path, ({disabled: true} if user_can_be_added?)
我能做到吗,是否有什么东西可以使用 splat 运算符让我到达那里...?
【问题讨论】:
-
Rails 在使用这样的助手时应该考虑布尔属性——使用
disabled: false应该可以工作,完全忽略disabled属性。
标签: html ruby-on-rails ruby