has_many :through with a foreign key?

前端 未结 1 1726
太阳男子
太阳男子 2020-12-24 02:44

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

I have 3 models: Apps, AppsGenres and

1条回答
  •  隐瞒了意图╮
    2020-12-24 02:50

    UPDATED Try 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
    

    0 讨论(0)
提交回复
热议问题