2015-06-19 69 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