我的目标是在视图中填充HTML表(schepary.html.haml(:
- if @plans != nil
%p display this if plans is not null
- if @plans == nil
%p= action_name
使用控制器中的@plans
数据:
def schedule
@plans = Order.all
end
我确定Order.all
返回数据。路由文件是:
get 'schedule', to: 'order_articles#schedule'
当我尝试执行此计划时,无效。输出为:
schedule
我试图检查plans
是否是null
,并在视图中使用代码。我做错了什么?
红宝石比其他流行的动态语言更严格,更理智的胁迫方案:
irb(main):001:0> !!nil
=> false
irb(main):002:0> !![]
=> true
irb(main):003:0> !!""
(irb):3: warning: string literal in condition
=> true
irb(main):004:0> !!0
=> true
除nil
和false
以外的所有内容都评估为true。nil
仅等于nil
。
Order.all
永远不会返回零,如果未找到记录,它将返回一个空的ActiveRecord::Collection
对象。这是一个类似结果对象的数组,告诉您数据库中没有任何内容。
因此,在处理集合时,您需要使用适当的方法,例如.any?
,.none?
等:
- if @plans.any?
%p display this if there are any plans.
- else
%p= action_name
您应该使用present?
,any?
或none?
代替nil?
。
如果您使用nil?
进行评估,它将始终返回false
,因为如果对象没有任何记录,它始终返回空数组[]
。
例如:
您的Order
表没有任何记录。
=> @plans = Order.all
=> @plans.nil?
=> false
=> @plans
=> []
如果有任何记录?
=> @plans = Order.all
=> @plans.nil?
=> false
=> @plans
=> [#<Order:0x007fa2832c0308
id: 1,
your_field: 'value'>]
建议#1
view(schedule.html.haml(:
- if @plans.present?
%p display this if plans is not null
- else
%p= action_name
建议#2
view(schedule.html.haml(:
- if @plans.any?
%p display this if plans is not null
- else
%p= action_name
建议#3
view(schedule.html.haml(:
- if @plans.none?
%p= action_name
- else
%p display this if plans is not null