我已閱讀過關於此的多個問題,但尚未找到適用於我的情況的答案。has_many:通過一個外鍵?
我有3種型號:Apps
,AppsGenres
和Genres
下面是每個的人的相關字段:
Apps
application_id
AppsGenres
genre_id
application_id
Genres
genre_id
這裏的關鍵是,我使用id
場不來自這些模型。
我需要根據那些application_id
和genre_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
你得到什麼SQL的權利嗎? – Rebitzele 2013-04-25 21:07:32