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