[英]How do I properly set up has and belongs to many association in rails active record
[英]Rails & Active Record: How do I access a sibling association?
我的電影模型has_many:trailers。 預告片中有一個is_feature_trailer的布爾列。
在我的trailerscontroller索引中,我渲染了所有trailers.where(is_feature_trailer:false)。
在_trailer.html.erb中,我想顯示關聯的功能預告片是否存在(如果trailer.movie.trailer.where(is_feature_trailer:true))。 但是我要避免在生成每個預告片時進行此查詢。
做到這一點的最佳方法是什么?
您可以指定associations
條件 。
#movie.rb
has_many :trailers
has_one :featured_trailer, -> { where(is_featured_trailer: true) }, class_name: "Trailer"
要么
您可以使用scope
#trailer.rb
scope :featured_trailer, ->(movie) { where(movie_id: movie.id, is_featured_trailer: true) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.