【问题标题】:Why is Ruby on Rails controller variable null?为什么 Ruby on Rails 控制器变量为空?
【发布时间】:2018-04-03 09:12:35
【问题描述】:

我的目标是在视图中填充一个 html 表格(schedule.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。我做错了什么?

【问题讨论】:

  • 请提供minimal reproducible example。什么是路由和控制器动作?你怎么称呼它?正在渲染什么?您的代码 sn-p 没有为任何人提供足够的信息来提供帮助。
  • 以上代码中没有任何内容表明@plans 将是nil。它应该始终是一个(可能为空的)数组。因此,您调用控制器操作/设置变量的方式一定有有问题,但我不知道是什么。
  • @Elyasin 这不会有什么不同。 nilNilClass 的单例实例;检查#nil? 与检查== nil 完全相同。
  • @F. LK,我认为使用nil 进行评估不会有效,请参阅下面的回答说明。

标签: ruby-on-rails ruby haml


【解决方案1】:

与其他流行的动态语言相比,Ruby 具有更严格和更健全的类型强制方案:

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

nilfalse 之外的所有内容都评估为真。 nil 只等于nil

Order.all 永远不会返回 nil,如果没有找到记录,它会返回一个空的 ActiveRecord::Collection 对象。它是一个类似结果对象的数组,告诉您数据库中没有任何内容。

所以在处理集合时需要使用适当的方法,例如.any?.none? 等:

- if @plans.any?
   %p display this if there are any plans.
- else
   %p= action_name

【讨论】:

    【解决方案2】:

    您应该使用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

    查看(schedule.html.haml):

    - if @plans.present?
      %p display this if plans is not null
    - else
      %p= action_name
    

    建议 #2

    查看(schedule.html.haml):

    - if @plans.any?
      %p display this if plans is not null
    - else
      %p= action_name
    

    建议 #3

    查看(schedule.html.haml):

    - if @plans.none?
      %p= action_name
    - else
      %p display this if plans is not null
    

    【讨论】:

    • 我会说any?none? 读起来好多了。 .present? 真正用于检查值/键是否已设置且不是空值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多