问题
I have models roughly as follows:
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
Given a @comment
(and an @author
with id
e.g. equal to 666
), I would like to get the articles
associated to an author
ordered by created_at
on the writing_associations
of the author
.
I tried the following (and many others) without success:
@comment
.articles_associable_by_author(@author)
.left_outer_joins(:writing_associations)
.order('writing_associations.created_at DESC')
.distinct
The above returns articles
associated to the author
that are not ordered by created_at
on the writing_associations
[1]. The related SQL query is:
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
How can I make the query to return the ordered records?
[1] Furthermore the LEFT OUTER JOINS doesn't care if the writing_associations
is associated to the author
. I think the JOINS should run something like ... LEFT OUTER JOIN 'writing_associations' ON 'writing_associations'.'article_id' = 'articles'.'id' AND 'writing_associations'.'author_id' = 666 ...
.
来源:https://stackoverflow.com/questions/54847669/how-to-make-a-mysql-query-to-return-the-ordered-records-on-a-joins-association