我有一个国家,有许多社区,有许多吸引人的地方
# Country
has_many :communities
# Community
has_many :attractions
# Attraction
belongs_to :community在我的Countries控制器中,我现在有如下内容:
def show
@communities = @country.communities.all.order('name asc').paginate(page: params[:page], per_page: 30)
end这给了我按名字订购的Communities。
我怎样才能用Community.attractions.count点菜,用最吸引人的地方点菜呢?
编辑
“为了上班,我稍微改变了穆罕默德的回答。
@communities = Community.joins(:country, :attractions).select("countries.*, communities.*, count(attractions.community_id) as attractions_count").group("communities.id, countries.id").order("attractions_count desc").where("countries.id = ?", @country.id).paginate(page: params[:page], per_page: 30)问题是,每个有0个景点的社区都没有被展示出来,我该如何解决这个问题?
发布于 2015-10-09 07:27:43
我会使用rails counter_cache basics.html
这意味着您将在Community表中有一个Community列,每次添加或删除吸引时都会更新该列。
# Community
has_many :attractions
# Attraction
belongs_to :community, counter_cache: true之后,您可以更容易地通过社区的attractions_count属性来订购社区。类似于:
@country.communities.order('attractions_count asc')Counter_cache的另一种选择:文化 gem
发布于 2015-10-08 15:42:52
尝试执行此查询
Community
.select("communities.*, count(attractions.community_id) as attractions_count")
.joins("LEFT JOIN `attractions` ON attractions.community_id = communities.id")
.group("communities.id")
.order("attractions_count desc")
.where("communities.country_id = ?", @country.id)对于这个查询,您必须只使用attractions表。我在加入countries表之前是错误的,而您只在communities表中找到带有country_id的社区,然后在where条件中找到countries.id。
希望这能帮到你。
https://stackoverflow.com/questions/33020004
复制相似问题