0

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?
3
  • 1
    "instead of returning a collection, it's returning an active record relation." They're the same thing. Commented Feb 15, 2016 at 21:03
  • I guess what I'm meaning to say.. I'm expecting to receive an output of Trailer objects. But instead, I'm getting < AtiveRecord Relation #23232 > so I don't know where it's going wrong Commented Feb 15, 2016 at 21:20
  • @JacksonCunningham it most likely mean that your SQL is wrong. To make sure relation is valid, call first, for example, on it. It should spit out either the object or the error, saying what's wrong with the query Commented Feb 15, 2016 at 21:33

1 Answer 1

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

would return all trailers, which movies have releases.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, this looks simple. I'll make sure it works then accept, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.