简体   繁体   中英

Querying multi level associations in rails

I have associations as below: Location Class

class Location < ActiveRecord::Base
  has_many :items
end

Item class

class Item < ActiveRecord::Base
  belongs_to :location
  belongs_to :category
end

Category class

class category < ActiveRecord::Base
  has_many :items
end

Now i want to query Location.categories (show all categories of location items). How can i achieve this?

It should be as simple as this:

class Location < ActiveRecord::Base
  has_many :items
  has_many :categories, :through => :items
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM