如何通过foreign_to引用的外部属性进行排序,其中有2个外键表的键

时间:2010-04-12 15:56:35

标签: ruby-on-rails ruby activerecord

我有一个与另一个模型有belongs_to关联的模型,如下所示

class Article
  belongs_to :author, :class_name => "User"
end

如果我想查找作者订购的特定类型的所有文章,我会做类似以下的

articles = Article.all(:includes => [:author], :order => "users.name")

但是,如果Article恰好有两个对User的引用,我该如何对:author进行排序?

class Article
  belongs_to :editor, :class_name => "User"
  belongs_to :author, :class_name => "User"
end

我试过了

articles = Article.all(:includes => [:author], :order => "users.name") 
#=> incorrect results
articles = Article.all(:includes => [:author], :order => "authors.name") 
#=> Exception Thrown

我的第一个尝试解决方案

半解决方案如下。这不是很明显,但看着我的日志,我想出来了。

class Article
  belongs_to :editor, :class_name => "User"
  belongs_to :author, :class_name => "User"
end

基本上你需要做以下

<击> articles = Article.all(:include => [:editor,:author], :order => 'articles_authors.name')

articles = Article.all(:include => [:editor,:author], :order => 'authors_articles.name') 

这是我错过的别名的命名(articles_authors)

这个问题是以下情况虽然看起来应该不起作用。

<击> articles = Article.all(:include => [:editor,:author], :order => 'authors_articles.name')

articles = Article.all(:include => [:editor,:author], :order => 'editors_articles.name')

如果您有UI表并希望将订单字段发送到控制器,则可能会出现问题。所以你可能想先在作者和编辑上订购。但是对于其中一个查询会失败(除非你动态地更改包含)

2 个答案:

答案 0 :(得分:5)

更新 - 将其添加到原始问题。

所以我想我已经钉了它。这不是很明显,但看着我的日志,我想出来了。

class Article
  belongs_to :editor, :class_name => "User"
  belongs_to :author, :class_name => "User"
end

基本上你需要做以下

<击> articles = Article.all(:include => [:editor,:author], :order => 'articles_authors.name')

articles = Article.all(:include => [:editor,:author], :order => 'authors_articles.name') 

这是我错过的别名的命名(articles_authors)

答案 1 :(得分:2)

这在ActiveRecord中称为表别名。当find方法多次连接同一个表时,表的别名确定如下:

Active Record uses table aliasing in the case that a table is referenced 
multiple times in a join. If a table is referenced only once, the standard table 
name is used. The second time, the table is aliased as 
#{reflection_name}_#{parent_table_name}. Indexes are appended for any more 
successive uses of the table name. 

有关详细信息,请参阅ActiveRecord documentation。搜索Table Aliasing以导航到特定部分。