Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Rails & Active Record: Complex SQL query

A have 3 Models: Trailer, Movie, Release. Trailer belongs_to a Movie, and a Movie has_many releases and has_many trailers.

I want to render the first trailer of each movie that has a release.

My approach was to create a scope in Trailer.rb:

scope :released, -> {
    joins(:movie).
    where("trailers.movie_id = movies.id").
    joins(:release).
    where.not( :release => nil )
  }

So that I could then call Trailer.released but my query is not working, instead of returning a collection, it's returning an active record relation.

  1. Where am I going wrong with my query?
  2. Is there a more efficient way to do this?

Upvotes: 0

Views: 139

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

scope :released, -> { joins(movie: :releases) }

would return all trailers, which movies have releases.

Upvotes: 1

Related Questions