2013-04-25 14 views
19

Ich habe mehrere Fragen dazu gelesen, muss aber noch eine Antwort finden, die für meine Situation funktioniert.has_many: durch mit einem Fremdschlüssel?

Ich habe 3 Modelle: Apps, AppsGenres und Genres

Hier sind die relevanten Felder aus jedem dieser:

Apps 
application_id 

AppsGenres 
genre_id 
application_id 

Genres 
genre_id 

Der Schlüssel hier ist, dass ich bin nicht das id Feld mit von diesen Modellen.

Ich muss die Tabellen basierend auf diesen application_id und genre_id Feldern zuordnen.

Hier ist, was ich zur Zeit habe, aber es wird immer mir die Abfrage nicht ich brauche:

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 

als Referenz, hier ist die Abfrage, die ich letztlich brauchen:

@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

Welche SQL sind Sie jetzt zu bekommen? – Rebitzele

Antwort

32

AKTUALISIERT Versuchen Sie dies:

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 

Mit Abfrage:

App.find(1).genres 

Es erzeugt:

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

Und query:

Genre.find(1).apps 

erzeugt:

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

Das gibt alle Genres für eine App zurück. Ich brauche alle Apps für ein Genre. – Shpigford

+0

Ok, ich habe den Code aktualisiert –

Verwandte Themen