Rails:如何检查列是否有值?

我怎么能做到这一点?

 ... Cell:  ...  

我想测试代理是否有一个单元格号,如果有,则显示条件内的内容。 我目前所做的似乎并不起作用; 它只显示“Cell:”。

思考?

这就是你要求的:

 <% for agent in @broker.agents %> <% unless agent.cell.blank? %> Cell: <%= agent.cell %> <% end %> <% end %> 

细胞? 无论单元格是nil还是空字符串,该方法都有效。 Rails为所有ActiveRecord属性添加了类似的function。 这看起来会更好一些:

 <% for agent in @broker.agents %>  Cell: <%= agent.cell? ? "none given" : agent.cell %>  <% end %> 

问号和冒号形成一个快速的“if?then:else”语句。 上面的代码中有两个问号,因为一个是方法名称单元格的一部分? 另一个是if / then / else结构的一部分。

我正在对这个问题给出一个非常详细的答案“ 如何检查列是否有值? ”。

首先,重要的是要注意属性中可以包含四种值。

  1. 值,即存储在数据库中的“nil”
  2. 值即“”一个没有空格的空字符串
  3. 带空格 “”的字符串。
  4. 数据库中存在的值,即非空字符串

以下是在这种情况下可以使用的所有现有方法(Ruby 2.2.2)的详细行为。

第一种方法: .empty?

  1. 对于nil值=>引发exception

     2.2.2 :037 > object.attribute => nil 2.2.2 :025 > object.attribute.empty? NoMethodError: undefined method `empty?' for nil:NilClass 
  2. 对于值,即“” 没有空格的空字符串

     2.2.2 :037 > object.attribute => "" 2.2.2 :025 > object.attribute.empty? true 
  3. 带空格 “”的字符串。

     2.2.2 :041 > object.attribute => " " 2.2.2 :042 > object.attribute.empty? => false 
  4. 数据库中存在的值,即非空字符串

     2.2.2 :045 > object.attribute => "some value" 2.2.2 :046 > object.attribute.empty? => false 

第二种方法: .nil?

  1. 值,即存储在数据库中的“nil”

     2.2.2 :049 > object.attribute => nil 2.2.2 :050 > object.attribute.nil? => true 
  2. 值即“”一个没有空格的空字符串

     2.2.2 :053 > object.attribute => "" 2.2.2 :054 > object.attribute.nil? => false 
  3. 带空格 “”的字符串。

     2.2.2 :057 > object.attribute => " " 2.2.2 :058 > object.attribute.nil? => false 
  4. 数据库中存在的值,即非空字符串

     2.2.2 :061 > object.attribute => "some value" 2.2.2 :062 > object.attribute.nil? => false 

第三种方法: .blank?

  1. 值,即存储在数据库中的“nil”

     2.2.2 :065 > object.attribute => nil 2.2.2 :066 > object.attribute.blank? => true 
  2. 值即“”一个没有空格的空字符串

     2.2.2 :069 > object.attribute => "" 2.2.2 :070 > object.attribute.blank? => true 
  3. 带空格 “”的字符串。

     2.2.2 :073 > object.attribute => " " 2.2.2 :074 > object.attribute.blank? => true 
  4. 数据库中存在的值,即非空字符串

     2.2.2 :075 > object.attribute => "some value" 2.2.2 :076 > object.attribute.blank? => false 

第四种方法:。 .present?

  1. 值,即存储在数据库中的“nil”

     2.2.2 :088 > object.attribute => nil 2.2.2 :089 > object.attribute.present? => false 
  2. 值即“”一个没有空格的空字符串

     2.2.2 :092 > object.attribute => "" 2.2.2 :093 > object.attribute.present? => false 
  3. 带空格 “”的字符串。

     2.2.2 :096 > object.attribute => " " 2.2.2 :097 > object.attribute.present? => false 
  4. 数据库中存在的值,即非空字符串

     2.2.2 :100 > object.attribute => "some value" 2.2.2 :101 > object.attribute.present? => true 

根据您所面临的情况,您可以使用四种中的任何一种。

谢谢

 if !agent.cell.blank? 

有用。

agent.cell? 似乎与agent.cell.blank一样工作? 在RoR。

 <% @broker.agents.each do |agent| %> ... <% unless agent.cell.empty? %> Cell: <%= agent.cell %> <% end %> ... <% end %> 

我发现使用#each, unlesscell.empty? 乍一看更易读,更容易理解。