计算协会关联范围内的记录

时间:2015-10-08 14:55:53

标签: ruby-on-rails ruby scope

我有一个Country,其中包含许多Communities Attractions

# Country
has_many :communities

# Community
has_many :attractions

# Attraction
belongs_to :community

如何构建一个从Country调用的范围,它将为我提供社区中的所有吸引力。

e.g。 @country.all_attractions

1 个答案:

答案 0 :(得分:2)

只需在has_many模型上添加throughCountry关系:

# Country
has_many :communities
has_many :attractions, through: :communities

# Community
belongs_to :country
has_many :attractions

# Attraction
belongs_to :community

然后你可以这样做:

@country.attractions
相关问题