gpt4 book ai didi

ruby-on-rails - 在有 2 个外部表键的情况下,如何按 belongs_to 引用的外部属性排序

转载 作者:数据小太阳 更新时间:2023-10-29 07:14:52 27 4
gpt4 key购买 nike

我有一个模型,它与另一个模型有一个 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 表并想将订单字段发送到 Controller ,这可能是个问题。所以你可能想先按作者顺序,然后按编辑顺序。但是其中一个查询会失败(除非您也动态更改包含)

最佳答案

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

所以我想我已经成功了。这不是很明显,但查看我的日志我想通了。

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

基本上你需要做以下事情

文章 = Article.all(:include => [:editor,:author], :order => 'articles_authors.name')

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

是我漏掉的别名的命名(articles_authors)

关于ruby-on-rails - 在有 2 个外部表键的情况下,如何按 belongs_to 引用的外部属性排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2623402/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com