代码之家  ›  专栏  ›  技术社区  ›  Will

如果有两个键指向外部表,我如何按外部属性为“属于引用”排序

  •  5
  • Will  · 技术社区  · 14 年前

    我有一个模型 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_name=>“用户”
    属于:author,:class_name=>“用户”
    结束
    

    基本上你需要做以下的事情

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

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

    我错过了别名的命名(文章作者)

    但问题是,以下内容似乎不起作用。

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

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

    如果您有一个UI表,并且想要将订单字段发送到控制器,那么这可能是一个问题。所以你可以先订购作者,然后再订购编辑。但对于其中一个查询,它将失败(除非您也动态更改include)

    2 回复  |  直到 14 年前
        1
  •  2
  •   Harish Shetty    14 年前

    这在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. 
    

    请参阅活动记录 documentation 了解更多详细信息。搜索 Table Aliasing 导航到特定部分。

        2
  •  5
  •   Will    14 年前

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

    所以我想我已经搞定了。这并不十分明显,但我看了看我的日志,就知道了。

    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') 
    

    我错过了别名的命名(文章作者)