如何多层次关联? [英] How to multi-level Associations?

查看:143
本文介绍了如何多层次关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的设置:

大陆 - > 国家 - > 城市 - > 发表

和我有

 类大陆< ActiveRecord的::基地
   的has_many:国家
结束类国家< ActiveRecord的::基地
  belongs_to的:大陆
  的has_many:城市
结束一流的城市< ActiveRecord的::基地
  belongs_to的:国家
  的has_many:帖子
结束后级< ActiveRecord的::基地
  belongs_to的:城市
结束

我如何得到所有大洲有帖子低谷此协会

我爱:

  @posts = Post.all@#posts.continents = GT; [{:ID => 1:名称=>中美国},{...}]


解决方案

您可以这样做:

  Continent.all(:加入=> {:国家= GT; {:城市=>:帖子}})uniq的。

或者这样:

 类大陆< ActiveRecord的::基地
  的has_many:国家  named_scope:with_post,:加入=> {:国家= GT; {:城市=> :帖子}}
结束# 接着
Continent.with_post.uniq

或者这样:

  Post.all(:包括=> {:城市=> {:国家= GT;:大陆}})。地图{|文章| post.city.country.continent} .uniq

或者这样:

 类帖子< ActiveRecord的::基地
  belongs_to的:城市  named_scope:include_continent,:包括=> {:城市=> {:国家= GT; :大陆}}  DEF大陆
    city​​.try(:国家)。尝试(:大陆)
  结束
结束# 接着
Post.include_continent.map(安培;:大陆).uniq

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

这篇关于如何多层次关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆