19

मैंने इसके बारे में कई प्रश्न पढ़े हैं, लेकिन अभी तक एक उत्तर नहीं मिला है जो मेरी स्थिति के लिए काम करता है। Apps, AppsGenres और Genreshas_many: एक विदेशी कुंजी के माध्यम से?

यहाँ उन में से प्रत्येक से प्रासंगिक क्षेत्र हैं:

मैं 3 मॉडल

Apps 
application_id 

AppsGenres 
genre_id 
application_id 

Genres 
genre_id 

यहाँ मुख्य बिंदु है मैं नहींid क्षेत्र का उपयोग कर रहा हूँ उन मॉडलों से।

मुझे उन application_id और genre_id फ़ील्ड के आधार पर तालिकाओं को जोड़ने की आवश्यकता है।

यहाँ मैं वर्तमान में क्या मिल गया है, लेकिन यह मुझे क्वेरी मैं की जरूरत नहीं हो रही है:

@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

क्या एसक्यूएल तुम अभी मिल रहा है? – Rebitzele

उत्तर

32

UPDATED:

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 

संदर्भ के लिए, क्वेरी मैं अंत में की जरूरत है इस प्रयास करें:

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 

और क्वेरी:

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 
+0

जो ऐप के लिए सभी शैलियों को लौटाता है। मुझे एक शैली के लिए सभी एप्स चाहिए। – Shpigford

+0

ठीक है, मैंने कोड अपडेट किया है –

संबंधित मुद्दे