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
Welche SQL sind Sie jetzt zu bekommen? – Rebitzele