1

I have a Country which has many Communities which have many Attractions

# Country
has_many :communities

# Community
has_many :attractions

# Attraction
belongs_to :community

How can I construct a scope that is called from the Country which will give me all the attractions in its communities.

e.g. @country.all_attractions

Mini John
  • 7,855
  • 9
  • 59
  • 108

1 Answers1

2

Simply add a has_many, through relation on your Country model:

# Country
has_many :communities
has_many :attractions, through: :communities

# Community
belongs_to :country
has_many :attractions

# Attraction
belongs_to :community

Then you can do:

@country.attractions
Drenmi
  • 8,492
  • 4
  • 42
  • 51
  • Hey Drenmi, thanks for that. Could you help me out with the `order.()` as well? I'm trying to order the communities by their attractions like so: `@communities = @country.communities.all.order('name asc').paginate(page: params[:page], per_page: 30)` – Mini John Oct 08 '15 at 15:07
  • @TheMiniJohn: You want to order them by the number of attractions? – Drenmi Oct 08 '15 at 15:09
  • Yes. but I can't find a reference of how to do that. – Mini John Oct 08 '15 at 15:10
  • @TheMiniJohn: There are some examples here on SO. E.g. http://stackoverflow.com/questions/16996618/rails-order-by-results-count-of-has-many-association. http://stackoverflow.com/questions/8696005/rails-3-activerecord-order-by-count-on-association, http://stackoverflow.com/questions/15478909/rails-3-activerecord-postgres-order-by-count-on-association. – Drenmi Oct 08 '15 at 15:13
  • I've read those but couldn't fit it into my case. I'm missing something :( – Mini John Oct 08 '15 at 15:19