2013-04-25 86 views
19

我已閱讀過關於此的多個問題,但尚未找到適用於我的情況的答案。has_many:通過一個外鍵?

我有3種型號:AppsAppsGenresGenres

下面是每個的人的相關字段:

Apps 
application_id 

AppsGenres 
genre_id 
application_id 

Genres 
genre_id 

這裏的關鍵是,我使用id來自這些模型。

我需要根據那些application_idgenre_id字段關聯表格。

這裏就是我目前得到的,但它沒有得到我,我需要查詢:

class Genre < ActiveRecord::Base 
    has_many :apps_genres, :primary_key => :application_id, :foreign_key => :application_id 
    has_many :apps, :through => :apps_genres 
end 

class AppsGenre < ActiveRecord::Base 
    belongs_to :app, :foreign_key => :application_id 
    belongs_to :genre, :foreign_key => :application_id, :primary_key => :application_id 
end 

class App < ActiveRecord::Base 
    has_many :apps_genres, :foreign_key => :application_id, :primary_key => :application_id 
    has_many :genres, :through => :apps_genres 
end 

以供參考,在這裏是查詢我最終需要:

@apps = Genre.find_by_genre_id(6000).apps 

SELECT "apps".* FROM "apps" 
    INNER JOIN "apps_genres" 
     ON "apps"."application_id" = "apps_genres"."application_id" 
    WHERE "apps_genres"."genre_id" = 6000 
+1

你得到什麼SQL的權利嗎? – Rebitzele 2013-04-25 21:07:32

回答

32

修訂試試這個:

class App < ActiveRecord::Base 
    has_many :apps_genres, :foreign_key => :application_id 
    has_many :genres, :through => :apps_genres 
end 

class AppsGenre < ActiveRecord::Base 
    belongs_to :genre, :foreign_key => :genre_id, :primary_key => :genre_id 
    belongs_to :app, :foreign_key => :application_id, :primary_key => :application_id 
end 

class Genre < ActiveRecord::Base 
    has_many :apps_genres, :foreign_key => :genre_id 
    has_many :apps, :through => :apps_genres 
end 

隨着查詢:

App.find(1).genres 

它產生:

SELECT `genres`.* FROM `genres` INNER JOIN `apps_genres` ON `genres`.`genre_id` = `apps_genres`.`genre_id` WHERE `apps_genres`.`application_id` = 1 

和查詢:

Genre.find(1).apps 

產生:

SELECT `apps`.* FROM `apps` INNER JOIN `apps_genres` ON `apps`.`application_id` = `apps_genres`.`application_id` WHERE `apps_genres`.`genre_id` = 1 
+0

返回應用程序的所有流派。我需要一個流派的所有應用程序。 – Shpigford 2013-04-26 02:41:22

+0

好的,我已經更新了代碼 – 2013-04-26 08:27:29