开发者

How to multi-level Associations?

开发者 https://www.devze.com 2023-03-04 14:15 出处:网络
I Have this setup: Continent -> Country -> City -> Post and I Have class Continent < ActiveRecord::Base

I Have this setup:

Continent -> Country -> City -> Post

and I Have

class Continent < ActiveRecord::Base
   has_many :countries
end

class Country < ActiveRecord::Base
  belongs_to :continent
  has_many :cities
end

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

class Post < ActiveRecord::Base
  belongs_to :city
end

How do I get all the Continents having posts trough this associations

Like:

@posts = Post.all

@posts.continents #=>开发者_开发知识库; [{:id=>1,:name=>"America"},{...}] 


You can do this:

Continent.all(:joins => {:countries => {:cities => :posts}}).uniq

Or this:

class Continent < ActiveRecord::Base
  has_many :countries

  named_scope :with_post, :joins => {:countries => {:cities => :posts}}
end

# And then
Continent.with_post.uniq

Or this:

Post.all(:include => {:city => {:country => :continent}}).map { |post| post.city.country.continent }.uniq

Or this:

class Post < ActiveRecord::Base
  belongs_to :city

  named_scope :include_continent, :include => {:city => {:country => :continent}}

  def continent
    city.try(:country).try(:continent)
  end
end

# And then
Post.include_continent.map(&:continent).uniq
0

精彩评论

暂无评论...
验证码 换一张
取 消