user2167582
user2167582

Reputation: 6388

How to use rails or sql to query through has_many association?

class Movie
  has_many :movie_genres
  has_many :genres, through: :movie_genres
end

I want find basically films that are not 'Short'.

I tried joins(:genres).where('genres.name is not ?', 'Short'), but seems to be returning movies whose first genre isn't 'Short' instead.

Upvotes: 0

Views: 155

Answers (2)

Naren Sisodiya
Naren Sisodiya

Reputation: 7288

You can use where with not like below

Movie.joins(:genres).where.not('genres.name = ?', 'Short')

Upvotes: 0

Pranav Prakash
Pranav Prakash

Reputation: 869

First you need to find out all movies which are having genre as 'Short' and then exclude those movies from final list. Try out something like following:

Movie.where.not(id: Movie.joins(:genres).where('genres.name = ?', 'Short').pluck(:id))

Upvotes: 1

Related Questions