I have three tables:
Posts
Keywordings
Keywords
Relevant fields in parens.
A Post
has_many :keywordings
has_many :keywords, :through => :keywordings
A Keywording(post_id, keyword_id)
belongs_to :post
belongs_to :keyword
A Keyword(name)
has_many :keywordings
has_many :posts, :through => :keywordings
I want to find all posts that have keywords that match any (by name) from a list, ordered by how many keywords got matched. I’m convinced this can all be done in SQL, but I’m at a loss.
If I have to do somethings in Ruby, fine, but preferably all in SQL. It does have to be fast.
Returns all posts that match at least one of a given list of keywords, ordered by the number of keywords matched:
If you just want the post IDs themselves, just use the subquery and the
ORDER BY.