Articles, Users, & Votes - Get Articles without Vote for User

#1

Hello.
(I’m sorry if I commit a duplicate with this question but I searched forehand and found nothing about it)

I have three classes:

  • Article (has_many votes, belongs_to user)
  • User (has_many votes, has_many articles)
  • Vote (belongs_to article, belongs_to user)

I want to get all Articles, which one User did not Vote yet.

Tried all the suggestions I found on the internet, but somehow they just dont work, for example, inside the Article model:

def self.with_no_votes_by(user)
includes(:votes).
references(:votes).
where.not(votes: { user_id: user.id })
end

This returns all Articles - why?
Can anyone help me get my mind around this problem, that seemed so simple first.

Thanks in advance.

#2

Try with this:

def self.with_no_votes_by(user)
  where.not(id: user.votes.map(&:article_id))
end
#3

Arcangel8801,

workes fine, thank you.

Had to change article_id to voteable_id though, because the votes are polymorphic, what I did not realize before.

Anyway, thanks a lot.

#4

Okay, any questions you can ask