[英]Table Join in Rails Active Record
我有一个电影模特
class Film < ActiveRecord::Base
has_many :film_genres
has_many :genres, through: :film_genres
end
体裁模型
class Genre < ActiveRecord::Base
has_many :film_genres
has_many :films, through: :film_genres
end
然后我有我的filmGenre模型
class FilmGenre < ActiveRecord::Base
belongs_to :film
belongs_to :genre
end
我尝试获取特定类型下控制器中的电影列表,但似乎无法参与其中。
def show
@films = ## need a join / select here to fetch all films with Genre.id of 4
end
使用includes
可以加入流派表,然后可以在where
条件中引用它:
@films = Film.includes(:genres).where(genres: {id: 4})
另外,从Genre
模型开始,获取所有类型4的电影可能会更容易:
@films = Genre.find(4).films
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.