我的模型大致如下:
class Article < ApplicationRecord
has_many :writing_associations
has_many :comments, :through => :writing_associations
has_many :author_article_associations
has_many :authors, :through => author_article_associations
end
class Comment < ApplicationRecord
has_many :writing_associations
has_many :articles, :through => :writing_associations
has_many :author_comment_associations
has_many :authors, :through => :author_comment_associations
def self.articles_associable_by_author(author)
author.articles
end
end
class Author < ApplicationRecord
has_many :author_article_associations
has_many :articles, :through => author_article_associations
has_many :author_comment_associations
has_many :comments, :through => author_comment_associations
end
class WritingAssociation < ApplicationRecord
belongs_to :author
belongs_to :article
belongs_to :comment
end
class AuthorArticleAssociation < ApplicationRecord
belongs_to :author
belongs_to :article
end
class AuthorCommentAssociation < ApplicationRecord
belongs_to :author
belongs_to :comment
end
给出一个@comment
(以及一个@author
等于id
的{{1}}),我想获得666
与articles
在author
的{{1}}上由created_at
排序的writing_associations
关联。
我尝试了以下(以及许多其他尝试)而没有成功:
author
以上返回与@comment
.articles_associable_by_author(@author)
.left_outer_joins(:writing_associations)
.order('writing_associations.created_at DESC')
.distinct
相关联的articles
,这些author
在created_at
[1]上未被writing_associations
排序。相关的SQL查询为:
SELECT
DISTINCT
`articles`.*
FROM
`articles`
INNER JOIN
`author_article_associations`
ON `articles`.`id` = `author_article_associations`.`article_id`
LEFT OUTER JOIN `writing_associations`
ON `writing_associations`.`article_id` = `articles`.`id`
WHERE `author_article_associations`.`creator_user_id` = 666
ORDER BY writing_associations.created_at DESC
如何进行查询以返回已排序的记录?
[1]此外,左外部联接不关心writing_associations
是否与author
相关联。我认为JOINS应该运行类似... LEFT OUTER JOIN 'writing_associations' ON 'writing_associations'.'article_id' = 'articles'.'id' AND 'writing_associations'.'author_id' = 666 ...
的东西。