开发者

Technique for dealing with nils in a deeply nested object model

I am working on a legacy rails application that has deeply nested associations. I have requirements that call for some of the deeply nested attributes to be bubbled up and displayed.

At the moment I am doing something like this to display results (using ActiveRecord Associations and Arrays)

model_a
  .collection_of_model_b
  .map(&:collection_model_c)
  .flatten
  .map(&:collection_model_d)
  .display_field

This approach worked with test data but once I started using real data I started noticing NilClass errors all over the place.

Please provide guidance in terms of technique, syntax, patterns that I can use to fetch this data.

Some approaches that I have thought about but have not pursued yet: 1) Break 开发者_如何学编程up the calls in separate lines doing a check for nils each time I go down a level. 2) Use straight sql ( find_by_sql ).


Use Array#compact:

>> [1, 2, nil, 3].compact
=> [1, 2, 3]

>> [[1, 2], [3, nil], [4]].map(&:compact)
=> [[1, 2], [3], [4]]


Do you have any has_may :through associations? like

class ModelA < ActiveRecord::Base
  ...
  has_many :model_bs
  has_many :model_cs, :through => :model_bs
  has_many :model_ds, :through => :model_cs
  ...
end

Personally, I think this still violates the Law of Demeter, as ModelA still knows a lot about the members of models B & C. But this at least abstracts it away and now you can just call:

model_a.model_ds.map(&:display_field)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜