【问题标题】:Emebedded Ruby: Short If Statement嵌入式 Ruby:短 If 语句
【发布时间】:2018-01-01 10:28:02
【问题描述】:

我目前正在学习 ruby​​,但我无法让我的嵌入式 ruby​​ 正常工作,我们将不胜感激。

我基本上是想在我的嵌入式 ruby​​ 中编写这个 if 语句的简短版本

<% entity.attributes.each do |key, value| %>
  <%= if key == "name"
        link_to @entity, edit_entity_path(entity)
      else 
        value
      end %>
<%= end %>

根据我的理解(和这个post)应该可以这样写

<% entity.attributes.each do |key, value| %>
  <%= key == "name" ? link_to @entity, edit_entity_path(entity) : value %>
<%= end %>

这似乎不起作用。我做错了什么?

Ralils 错误消息: 语法错误,意外 tIVAR,期待 keyword_do 或 '{' 或 '(' ...ey == "name") ? ...

提前感谢您的帮助

【问题讨论】:

  • 在 Ruby 中使用三元运算符时,您的 if : else 必须每个都用括号括起来,或者如果在其中传递函数,它们需要使用 function(args) 形式而不是空格(@ 除外987654326@ 等)。例如true ? true.is_a? TrueClass : false 会引发错误,但true ? true.is_a?(TrueClass) : false 不会。如果您使用三元运算符返回,您可以像 assertion ? (return something) : (return something_else)

标签: ruby-on-rails if-statement embedded-ruby


【解决方案1】:

有一个 link_to_if 助手,它将您的代码重构为:

<% entity.attributes.each do |key, value| %>
  <%= link_to_if key == "name", value, edit_entity_path(entity) %>
<% end %>

【讨论】:

    【解决方案2】:

    您必须将link_to 的参数括在括号中:

    <%= key == "name" ? link_to(@entity, edit_entity_path(entity)) : value %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-26
      • 2014-12-19
      • 2021-08-20
      • 2017-11-14
      • 1970-01-01
      • 2022-11-26
      • 2012-07-05
      • 1970-01-01
      相关资源
      最近更新 更多