Rails:如何检查列是否有值? [英] Rails: How do I check if a column has a value?
问题描述
如何完成此操作?
<%for agent in @ broker.agents%>
...
<%if agent.cell%>< span class =cell-number>单元格:<%= agent.cell%>< / span> <%end%>
...
<%end%>
我想测试代理是否有单元格号,如果是,条件。我目前似乎没有工作;
这是您要求的:
<%for agent in @ broker.agents%>
<%unless agent.cell.blank? %>
< span class =cell-number>单元格:<%= agent.cell%>< / span>
<%end%>
<%end%>
单元格?方法的作用是单元格是nil还是空字符串。 Rails为所有ActiveRecord属性添加类似的函数。这将看起来更好一些:
<%for agent in @ broker.agents%>
< span class =cell-number>
单元格:<%= agent.cell? ? none given:agent.cell%>
< / span>
<%end%>
问号和冒号形成快速的if?then:else语句。在上面的代码中有两个问号,因为一个是方法名单元格的一部分?另一个是if / then / else结构的一部分。
How can I accomplish this?
<% for agent in @broker.agents %>
...
<% if agent.cell %><span class="cell-number">Cell: <%= agent.cell %></span><% end %>
...
<% end %>
I want to test to see if the agent has a cell number, and if so, display what's inside the conditional. What I have currently doesn't seem to work; it just displays "Cell: ".
Thoughts?
This is what you asked for:
<% for agent in @broker.agents %>
<% unless agent.cell.blank? %>
<span class="cell-number">Cell: <%= agent.cell %></span>
<% end %>
<% end %>
The cell? method works whether cell is nil or an empty string. Rails adds similar functions for all ActiveRecord attributes. This will look a little nicer:
<% for agent in @broker.agents %>
<span class="cell-number">
Cell: <%= agent.cell? ? "none given" : agent.cell %>
</span>
<% end %>
The question mark and colon form a quick "if ? then : else" statement. There are two question marks in the code above because one is part of the method name cell? and the other is a part of the if/then/else construction.
这篇关于Rails:如何检查列是否有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!