19

Я читал несколько вопросов об этом, но еще не нашел ответа, который работает для моей ситуации.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 
+1

Что SQL вы получаете прямо сейчас? – Rebitzele

ответ

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

+0

Хорошо, я обновил код –