2013-07-23 11 views
5

के साथ एन + 1 क्वेरी मेरे पास दो मॉडल हैं।रेल + पॉलिओर्फिक एसोसिएशन

एल्बम

class Album < ActiveRecord::Base 
    has_one :post, as: :post_module, dependent: :destroy 
end 

पोस्ट

class Post < ActiveRecord::Base 
    belongs_to :post_module, polymorphic: true 
end 

(जो शीर्षक विशेषता है) और यहाँ

<% @albums.each do |album| %> 
    <tr> 
    <td> 
     <%= link_to album.post.title, edit_admin_album_path(album) %>&nbsp;<br/> 
    </td> 
    </tr> 
<% end %> 

मैं :includes और :references उपयोग करने के लिए एन से बचने की कोशिश की मेरे टेम्पलेट है + 1 क्वेरी

def index 
    @albums = Album.includes(:post).references(:post).to_a 
end 

लेकिन ऐसा लगता है कि एन + 1 क्वेरी अभी भी होती है। इसके साथ क्या गलत है?

SQL (0.2ms) SELECT `albums`.`id` AS t0_r0, `albums`.`product_num` AS t0_r1, `albums`.`created_at` AS t0_r2, `albums`.`updated_at` AS t0_r3, `posts`.`id` AS t1_r0, `posts`.`title` AS t1_r1, `posts`.`date` AS t1_r2, `posts`.`post_module_id` AS t1_r3, `posts`.`post_module_type` AS t1_r4, `posts`.`created_at` AS t1_r5, `posts`.`updated_at` AS t1_r6 FROM `albums` LEFT OUTER JOIN `posts` ON `posts`.`post_module_id` = `albums`.`id` AND `posts`.`post_module_type` = 'Album' 
Post Load (0.3ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 18 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1 
Post Load (0.2ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 20 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1 
Post Load (0.2ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 21 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1 
Post Load (0.2ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 22 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1 
Post Load (0.1ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`post_module_id` = 23 AND `posts`.`post_module_type` = 'Album' ORDER BY `posts`.`id` ASC LIMIT 1 
+0

प्रयास करें ऐसा लगता है एन 1 भी तब होता है जब मैं में फोन नहीं है 'album.post.title ' @album = album.all – synthresin

+0

के साथ प्रत्येक लूप album.includes (: पोस्ट) केवल –

+0

यह मुझे एक ही परिणाम प्राप्त करता है :( – synthresin

उत्तर

0

देखने के लिए कि क्या यह उत्तर लागू होता है आप

Ruby on Rails: :include on a polymorphic association with submodels

+0

यह काम नहीं करता है :( – synthresin

+0

ठीक है, तो इसे आजमाएं http://stackoverflow.com/questions/2390017/ruby-on-rails-include-on-a-polymorphic-association-with-submodels – Benj

+0

मेरी स्थिति में फिट होने के लिए, मुझे 'पोस्ट' मॉडल से पूछताछ करनी चाहिए .. – synthresin

1

आप एक बहुरूपी संघ में उत्सुक लोड हो रहा है कोशिश कर रहे हैं के लिए।

कृपया अधिक जानकारी के लिए निम्न

साइट उल्लेख

Polymorphic Association and Eager Loading Issues

Album.all.includes(:post => :post_module) 
+0

यह त्रुटि फेंकता है 'एसोसिएशन नाम' पॉलिमॉर्फिक 'टीटी नहीं मिला – synthresin

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