2015-06-19 66 views
0

我有一个电影模式表加入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 

林试图得到一个在特定流派下的控制器中的电影列表,但似乎无法加入工作。通过与起始

@films = Film.includes(:genres).where(genres: {id: 4}) 

或者,它可能是更容易得到所有类型4的电影:

def show 
    @films = ## need a join/select here to fetch all films with Genre.id of 4 
    end 
+0

你得到了什么样的错误? – rii

回答

2

使用includes加入流派表,然后就可以在where条件引用它Genre型号:

@films = Genre.find(4).films 
+1

谢谢。两者都有效,因为它读得更好,所以选择了第二种选择。 – fauxdev