Rails:检查嵌套属性的存在

时间:2011-04-18 13:05:49

标签: ruby-on-rails

如果我有以下嵌套模型关系(所有has_many): 国家<城市<街道<舍

在节目视图中,我如何检查特定国家/地区是否有任何房屋?

编辑: 使用map方法添加建议的链接方法(首先尝试映射到街道)。到目前为止,它并没有限制记录

<% @countries.each do |country| %>
  <% if country.cities.map(&:streets).any? %>
    ....
  <% end %>
<% end %>

1 个答案:

答案 0 :(得分:2)

您可以致电或@country.cities.map(&:streets).flatten.map(&:homes).present?@country.cities.map(&:streets).map(&:homes).any?

<% if @country.cities.map(&:streets).flatten.map(&:homes).flatten.any? %>
  Tro-lol-lo yo-lo-puki
<% end %>

此外,您可以将此长行包装到模型方法中:

class Country < ActiveRecord::Base
  def any_homes?
    cities.map(&:streets).flatten.map(&:homes).flatten.any?
  end
end

用法

<% if @country.any_homes? %>
  Tro-lol-lo yo-lo-puki
<% end %>

当然,它看起来像是一个很好的重构数据结构! 想要重构!

相关问题