2013-07-23 14 views
5

Mam dwa modele.Zapytanie N + 1 z polimorficznym skojarzeniem szyn

Album

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

post (który ma tytuł atrybutu)

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

i tu jest mój szablon

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

Próbowałem użyć :includes i :references uniknąć N + 1 zapytanie.

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

Ale wygląda na to, że zapytanie N + 1 nadal występuje. Co jest z tym nie tak?

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

Wydaje N + 1 występuje nawet wtedy, kiedy nie zadzwonić 'album.post.title” w każda pętla z @album = Album.all – synthresin

+0

spróbować Album.includes (: post) tylko –

+0

robi mi sam wynik :( – synthresin

Odpowiedz

1

Próbujesz chętny załadunek w polimorficzny stowarzyszenia.

Zapoznaj następującą witrynę Więcej szczegółów

Polymorphic Association and Eager Loading Issues

spróbuj

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

to zgłasza błąd "Stowarzyszenie o nazwie" polimorficzne "nie zostało znalezione" TT – synthresin

Powiązane problemy