如何进行多级公会?

发布于 2024-11-06 05:23:49 字数 594 浏览 0 评论 0原文

我有这样的设置:

Continent -> 国家 -> 城市 -> Post

和我

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

如何通过此关联获得所有有帖子的大洲,

例如:

@posts = Post.all

@posts.continents #=> [{:id=>1,:name=>"America"},{...}] 

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"},{...}] 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪是无色的血 2024-11-13 05:23:49

你可以这样做:

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

或这样:

class Continent < ActiveRecord::Base
  has_many :countries

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

# And then
Continent.with_post.uniq

或这样:

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

或这样:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文