Pet*_*xey 5 html ruby ruby-on-rails
在Rails中有很多次我希望能够仅在属性具有特定值时才能向某个属性添加属性.
让我给你举个例子.假设我想禁用基于特定属性的按钮,例如check_if_user_can_be_added:
link_to 'Create account', new_user_path, disabled: (user_can_be_added?)
Run Code Online (Sandbox Code Playgroud)
这一切看起来都很好,除了禁用恰好在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
Run Code Online (Sandbox Code Playgroud)
获得这个意味着您需要一个类似于以下的解决方案,首先设置选项哈希,然后将其传递给:
options = user_can_be_added? ? {disabled: true} : {}
link_to 'Create account', new_user_path, options
Run Code Online (Sandbox Code Playgroud)
这不起作用,但相信Ruby的美丽,我怀疑那里有类似的东西.这基本上就是我想要做的
link_to 'Create account', new_user_path, ({disabled: true} if user_can_be_added?)
Run Code Online (Sandbox Code Playgroud)
我可以这样做,是否有一些使用splat运算符的东西让我在那里......?
您可以设置nil以使Rails忽略该属性:
link_to 'Create account', new_user_path, disabled: (user_can_be_added? ? true : nil)
Run Code Online (Sandbox Code Playgroud)
对于这种特殊情况,您也可以使用|| 像这样:
link_to 'Create account', new_user_path, disabled: (user_can_be_added? || nil)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2172 次 |
| 最近记录: |