新手问题 model 值为空,为何会报错?

QueXuQ · 2012年10月18日 · 最后由 Rei 回复于 2012年10月18日 · 2452 次阅读

两个 model 中的关系如下:

class A < ActiveRecord::Base
  has_mang :Bs
end

class B < ActiveRecord::Base
  belongs_to :A
end

B 中有字段 name A 中有字段 price

当我调用B.first.name的时候而此时的 price 为控制,则在页面中不会显示。

但是如果当 A 的 price 中为空的话,通过 B 去调用就会报错,如:B.first.A.price这样就会报错,就算你if B.first.A.price,只是判断,也会出现错误。

B.first.A如果为空,也不会有错误出现。

请问为什么B.first.A.price会出现没有此方法的错误呢?

缺了最重要的 Exception 信息

@QueXuQ 把错误信息打出来吧

A 为 nil 的时候就算if B.first.A.price 也会报错是因为你在 nil 上要了 price...

#1 楼 @chechaoyang #2 楼 @tiseheaini

搞懂了,原来就像 @leozwa 说的那样。因为 A 是 nil。 那请问我应该怎么样才可以让他出现空值,而不要报错呢?

- if B.first.A
  = B.first.A.price

这样是好办法吗?

= B.first.A.try(:price)

需要 登录 后方可回复, 如果你还没有账号请 注册新账号