加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何通过foreign_to引用的外部属性进行排序,其

发布时间:2020-12-17 03:26:11 所属栏目:百科 来源:网络整理
导读:我有一个Model,它与另一个Model有belongs_to关联,如下所示 class Article belongs_to :author,:class_name = "User"end 如果我想找到作者订购的特定类型的所有文章,我会做类似以下的事情 articles = Article.all(:includes = [:author],:order = "users.name
我有一个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.搜索表别名以导航到特定部分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读