blankammo
blankammo

Reputation: 119

has_many and has_many relation

I have Country, City, Shop models

class Country < ActiveRecord::Base
  has_many :cities
end

class City < ActiveRecord::Base
  belongs_to :country
  has_many :shops 
end

class Shop < ActiveRecord::Base
  belongs_to :city
end

How can I get country.shops in activerecord? (get all shops in country)

I usually use Country.cities.collect { |c| c.shops } but this is not activerecord object.

I have considered add country_id on shop model and set has_many relation but I think it's not best way.

Upvotes: 0

Views: 176

Answers (2)

Troy
Troy

Reputation: 5399

In Country, add a has_many :through relation:

class Country < ActiveRecord::Base
  has_many :cities
  has_many :shops, through: :cities
end

Now you can write country.shops and receive an appropriate ActiveRecord relation where you can say stuff like country.shops.where name:"Nieman Marcus" and other such queries.

Upvotes: 1

super_fish
super_fish

Reputation: 107

you can def a method in Class Country

def all_shops
  self.cities.collect { |c| c.shops }
end

you alse can use Mongoid::Tree

def all_shops
  Shop.where(:parent_ids => self.id)
end

Upvotes: 0

Related Questions