按子属性对Activerecord查询进行分组

时间:2020-03-06 14:38:37  来源:igfitidea点击:

是否可以使用子级的属性对查询进行分组?

Post.find(:all, :include => [ :authors, :comments ], :group=>'authors.city')

不起作用。

但是,我可以使用author.city作为条件的一部分。

解决方案

如果那是我们使用的,则:group参数的语法错误,应为:

Post.find(:all, :include => [ :author, :comments ], :group=>'authors.city')

确保:author和:comments关联正确。如果'authors'是实际的表名,则在Post模型和Author模型中需要一个'has_one:author'关联。

关联也必须正确:

class Post < AR:Base
   belongs_to :author
   has_many :comments
 end

 class Author < AR:Base
   has_many :posts
 end

 class Comment < AR:Base
   belongs_to :post
 end

和数据库模式:

posts
   id
   author_id
 authors
   id
 comments
   id
   post_id

这将使查询正确运行,但是,现在我得到的结果是错误的:使用:include时,似乎没有应用:group子句。

查看日志文件中生成的查询,我们通常可以将该查询粘贴到我们喜欢的MySQL工具中,以获得更详细的错误。

我们实际上可能需要提供一个聚合函数来使数据库正确分组(这在MySQL中发生,而不是有时出现语法错误)。

作者是否应包括在内?

Post.find(:all, :include => [ :authors, :comments ], :group=>'authors.city')

解决方案是强制进行必要的连接,以便ActiveRecord可以解析" authors.city":

Post.find(:all, :include => [ :author, :comments ], :joins=>"INNER JOIN authors ON posts.author_id=authors.id", :group=>'authors.city')