samedi 5 juin 2021

Improving a query. One book for each author

I need an hand to improve this query

def interesting_books
  Book.joins(:genre)
    .where(author: interesting_authors.sample(5))
    .where('ratings >= 4')
    .random_order
    .where.not(id: black_books)
    .limit(3)
end

def interesting_authors
 @interesting_authors ||= (authors_commented_books + authors_watched_books).uniq
end

def authors_commented_books
 @authors_commented_books ||= current_user.commented_books.pluck(:author).uniq
end

def authors_watched_books
 @authors_watched_books ||= current_user.watched_books.pluck(:author).uniq
end

now, in this way if in the .where(author: interesting_authors.sample(5)) i have authors like "Shakespear", "Twain" , "Fitzgerald", "Wilde" and "Darwin"... it shows only 3 books (.limit(3)) made by "Shakespear". Result: "Macbeth", "Othello" and "The Tempest".

BUT I want to show 3 books made by different (selected) authors. Like "Othello", "The Great Gatsby" and "Dorian Gray".

How to do?

Aucun commentaire:

Enregistrer un commentaire