我有一个Model,它与另一个Model有belongs_to关联,如下所示
class Article belongs_to :author,:class_name => "User" end
如果我想找到作者订购的特定类型的所有文章,我会做类似以下的事情
articles = Article.all(:includes => [:author],:order => "users.name")
但是,如果文章恰好有两个对用户的引用,我该如何排序:作者?
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" 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,:order =>’authors_articles.name’)
articles = Article.all(:include => [:editor,:order => 'editors_articles.name')
如果您有UI表并希望将订单字段发送到控制器,则可能会出现问题.所以你可能想先在作者和编辑上订购.但是对于其中一个查询会失败(除非您动态更改包含)
解决方法
这在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.搜索表别名以导航到特定部分.