Skip to content

Instantly share code, notes, and snippets.

@dmastylo dmastylo/double_nest.rb
Last active Aug 29, 2015

Embed
What would you like to do?
Getting results from a doubly nested relationships that has a count of > 0
class Category < ActiveRecord::Base
# Relationships
# ========================================================
has_many :shops
end
class Shop < ActiveRecord::Base
# Relationships
# ========================================================
belongs_to :category
has_many :items
end
class Item < ActiveRecord::Base
# Relationships
# ========================================================
belongs_to :shop
end
categories = joins(:shops).uniq
categories.map do |category|
shops = category.shops.delete_if { |shop| shop.items.count == 0 }
OpenStruct.new({ id: category.id, name: category.name, shops: shops })
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.