我有这个设置:
Continent
-> Country
-> City
-> 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
我怎样才能让所有大洲都通过这个协会发帖
Like:
@posts = Post.all
@posts.continents #=> [{:id=>1,:name=>"America"},{...}]
你可以这样做:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)