has_many:通过外键?

Shp*_*ord 22 ruby-on-rails foreign-keys associations has-many-through

我已经阅读了多个有关此问题的问题,但尚未找到适合我情况的答案.

我有3种型号:Apps,AppsGenresGenres

以下是每个相关领域:

Apps
application_id

AppsGenres
genre_id
application_id

Genres
genre_id
Run Code Online (Sandbox Code Playgroud)

这里的关键是我没有使用id这些模型中的字段.

我需要根据这些application_idgenre_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
Run Code Online (Sandbox Code Playgroud)

作为参考,这是我最终需要的查询:

@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
Run Code Online (Sandbox Code Playgroud)

Ant*_*yev 41

更新试试这个:

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
Run Code Online (Sandbox Code Playgroud)

带查询:

App.find(1).genres
Run Code Online (Sandbox Code Playgroud)

它产生:

SELECT `genres`.* FROM `genres` INNER JOIN `apps_genres` ON `genres`.`genre_id` = `apps_genres`.`genre_id` WHERE `apps_genres`.`application_id` = 1
Run Code Online (Sandbox Code Playgroud)

并查询:

Genre.find(1).apps
Run Code Online (Sandbox Code Playgroud)

产生:

SELECT `apps`.* FROM `apps` INNER JOIN `apps_genres` ON `apps`.`application_id` = `apps_genres`.`application_id` WHERE `apps_genres`.`genre_id` = 1
Run Code Online (Sandbox Code Playgroud)