Ruby-on-rails has_many :通过外键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16222838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:52:36  来源:igfitidea点击:

has_many :through with a foreign key?

ruby-on-railsforeign-keysassociationshas-many-through

提问by Shpigford

I've read multiple questions about this, but have yet to find an answer that works for my situation.

我已经阅读了多个关于此的问题,但还没有找到适合我的情况的答案。

I have 3 models: Apps, AppsGenresand Genres

我有 3 个模型:Apps,AppsGenresGenres

Here are the pertinent fields from each of those:

以下是每个领域的相关领域:

Apps
application_id

AppsGenres
genre_id
application_id

Genres
genre_id

The key here is that I'm notusing the idfield from those models.

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

I need to associate the tables based on those application_idand genre_idfields.

我需要根据这些application_idgenre_id字段关联表。

Here's what I've currently got, but it's not getting me the query I need:

这是我目前所拥有的,但它没有让我得到我需要的查询:

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

For reference, here is the query I ultimately need:

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

@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

回答by Anton Grigoryev

UPDATEDTry this:

更新试试这个:

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

With query:

随着查询:

App.find(1).genres

It generates:

它生成:

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

And query:

并查询:

Genre.find(1).apps

generates:

产生:

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