Reputation: 5073
My Movie model has_many :trailers. Trailers has a boolean column for is_feature_trailer.
In my trailers_controller index, I'm rendering all trailers.where(is_feature_trailer: false).
In _trailer.html.erb I want to show the associated feature trailer if it exists ( if trailer.movie.trailer.where(is_feature_trailer: true) ). But I want to avoid making this query as I'm rendering each trailer.
What's the best way to accomplish this?
Upvotes: 0
Views: 500
Reputation: 33552
You can specify conditions on associations
.
#movie.rb
has_many :trailers
has_one :featured_trailer, -> { where(is_featured_trailer: true) }, class_name: "Trailer"
OR
You can use a scope
#trailer.rb
scope :featured_trailer, ->(movie) { where(movie_id: movie.id, is_featured_trailer: true) }
Upvotes: 1