Rails3 - 如何多层次的关联? [英] Rails3 - How To Multi-level Associations?

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

问题描述

我有这样的设置:

- > 国家 - > 城市 - >

和我有

 类大陆<的ActiveRecord :: Base的
   的has_many:国家
结束



类国家<的ActiveRecord :: Base的
  belongs_to的:大陆
  的has_many:城市
结束



一流的城市与LT;的ActiveRecord :: Base的
  belongs_to的:国家
  的has_many:帖子
结束



类岗位<的ActiveRecord :: Base的
  belongs_to的:城市
结束
 

我怎么各大洲有帖子低谷这个协会

这样的:

  @posts = Post.all

    @ posts.continents#=> [{:ID => 1:NAME =>中美国},{...}]
 

解决方案

你可以这样做:

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

或者这样:

 类大陆<的ActiveRecord :: Base的
  的has_many:国家

  named_scope:with_post,:加入=> {:国家=> {:城市=> :职位}}
结束

# 接着
Continent.with_post.uniq
 

或者这样:

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

或者这样:

 类岗位<的ActiveRecord :: Base的
  belongs_to的:城市

  named_scope:include_continent,:包括=> {:城市=> {:国=> :大陆}}

  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

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

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