使用外键的has_many :through?

25

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

我有3个模型:AppsAppsGenresGenres

以下是每个模型的相关字段:

Apps
application_id

AppsGenres
genre_id
application_id

Genres
genre_id

关键在于我没有使用那些模型中的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

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

@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
1个回答

47

更新 请尝试以下方法:

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

And查询:

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

返回一个应用程序的所有类型。我需要一个类型的所有应用程序。 - Shpigford

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接