3

If I have the following nested model relationships (all has_many): Countries < Cities < Streets < Homes

In a show view, how can I check if a particular Country has any homes?

Edit: Adding the suggested method of chaining with the map method (first try to map to streets). So far it's not restricting the records

<% @countries.each do |country| %>
  <% if country.cities.map(&:streets).any? %>
    ....
  <% end %>
<% end %>
1
  • country.cities.map(&:streets).flatten.any? Commented Apr 18, 2011 at 14:00

1 Answer 1

2

You can call or @country.cities.map(&:streets).flatten.map(&:homes).present? or @country.cities.map(&:streets).map(&:homes).any?

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

Also you can wrap this long line into your model method:

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

Usage

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

And of course it looks like a good data structure for refactoring! It wants to be refactored!

Sign up to request clarification or add additional context in comments.

3 Comments

Hi. This looks like it should work. However it is not cutting out countries without homes. Each nesting level is linked by a (belongs_to/has_many) connection. I'll put my method in my original post.
I don't understand you. Also there is a bug in my code. I'm going to fix it now
Works now. Thanks. I'll go away and google refactoring to see if I can figure out what you mean. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.