references rails inverse_of has_many has_and_belongs_to_many foreign belong ruby-on-rails foreign-keys associations has-many-through

ruby-on-rails - inverse_of - rails references



has_many: a través de una clave externa? (1)

ACTUALIZADO Prueba esto:

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

Con consulta:

App.find(1).genres

Genera:

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

Y consulta:

Genre.find(1).apps

genera:

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

He leído varias preguntas sobre esto, pero todavía tengo que encontrar una respuesta que funcione para mi situación.

Tengo 3 modelos: Apps , AppsGenres y Genres

Aquí están los campos pertinentes de cada uno de esos:

Apps application_id AppsGenres genre_id application_id Genres genre_id

La clave aquí es que no estoy usando el campo de id de esos modelos.

Necesito asociar las tablas basadas en esos campos application_id y genre_id .

Esto es lo que tengo actualmente, pero no me está dando la consulta que necesito:

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

Para referencia, aquí está la consulta que finalmente necesito:

@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