2013-04-25 22 views
19

Przeczytałem wiele pytań na ten temat, ale jeszcze nie znalazłem odpowiedzi, która pasuje do mojej sytuacji.has_many: za pomocą klucza obcego?

mam 3 modele: Apps, AppsGenres i Genres

Oto stosowne pola z każdego z tych:

Apps 
application_id 

AppsGenres 
genre_id 
application_id 

Genres 
genre_id 

Kluczem tutaj jest to, że jestem nie użyciu pola id z tych modeli.

Muszę powiązać tabele na podstawie tych pól application_id i genre_id.

Oto co ja obecnie mam, ale nie trafia do mnie zapytania, czego potrzebuję:

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 

Dla porównania, tutaj jest kwerenda I ostatecznie potrzebować:

@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

Co SQL są otrzymujesz teraz? – Rebitzele

Odpowiedz

32

AKTUALIZACJA Wypróbuj to:

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 

Z zapytaniem:

App.find(1).genres 

Generuje:

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

I zapytanie:

Genre.find(1).apps 

generuje:

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

Zwraca wszystkie gatunki aplikacji. Potrzebuję wszystkich aplikacji dla gatunku. – Shpigford

+0

OK, zaktualizowałem kod –

Powiązane problemy