【问题标题】:Rails 4: conditional display not working inside viewRails 4:条件显示在视图内不起作用
【发布时间】:2015-10-23 00:42:00
【问题描述】:

在我的 Rails 4 应用程序中,有一个 Post 模型,具有 :copy:short_copy 属性。

在 Posts#Show 视图中,如果 :short_copy 由用户定义,我想显示它,否则 :copy

所以,我实现了以下代码:

<% if @post.short_copy %>
  <%= @post.short_copy %>
<% else %>
  <%= @post.copy %>
<% end %>

问题:当:short_copy 被定义时,它会显示出来,但是,当它没有被定义时(并且:copy 定义的),:copy 不会显示出来.

这段代码有问题吗?

【问题讨论】:

  • @post.short_copy 是否可能等于空字符串?
  • 是的,这是可能的,你是对的。然后,如果@post.short_copy 不是 nil,那么我们显示它,什么也没有出现。那么,我需要像unless @post.short_copy.nil? || @post.short_copy.empty? 这样的事情来测试它吗?
  • 是的。确切地。我会做@post.short_copy.nil?,但是你需要确保你的用户输入正确保存或者是nil。 :)

标签: ruby-on-rails ruby ruby-on-rails-4 if-statement view


【解决方案1】:

使用String#blank? 来检查一个值 - 一个空字符串仍然是true

<% if !@post.short_copy.blank? %>
  <%= @post.short_copy %>
<% else %>
  <%= @post.copy %>
<% end %>

【讨论】:

  • @post.short_copy.present? 也可以使用,如果您不想在表达式中使用 !
【解决方案2】:

我认为您的代码本质上没有问题,但您可能会被@post.short_copy 的值误导。除非它是nilfalse,否则&lt;% if @post.short_copy %&gt; 将运行。我会想象@post.short_copy = '',因此视图中没有显示任何内容。

【讨论】:

    【解决方案3】:

    我只是运行这个 sn-p:

    2.1.1 :002 > if("")
    2.1.1 :003?>   printf "yes"
    2.1.1 :004?>   else
    2.1.1 :005 >     printf "no"
    2.1.1 :006?>   end
    (irb):6: warning: string literal in condition
    yes => nil 
    

    所以 - 如果 short_copy 是空字符串,它将评估为真。所以试试这个:

    2.1.1 :020 > unless("".empty?)
    2.1.1 :021?>   printf "yes"
    2.1.1 :022?>   else
    2.1.1 :023 >     printf "no"
    2.1.1 :024?>   end
    no => nil 
    

    【讨论】:

      【解决方案4】:

      我总是使用string.blank? 来检查是否为 nil 或空字符串。如果字段是数组,则使用 array.empty?。所以在你的情况下,你可以使用空白吗?

      <% unless @post.short_copy.blank? %> <%= @post.short_copy %> <% else %> <%= @post.copy %> <% end %>

      【讨论】:

        猜你喜欢
        • 2014-01-12
        • 2013-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        相关资源
        最近更新 更多