mysql - N+1 query with rails polymorphic association -


i have 2 models.

album

class album < activerecord::base     has_one :post, as: :post_module, dependent: :destroy end 

post (which has title attribute)

class post < activerecord::base     belongs_to :post_module, polymorphic: true end 

and here template

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

i tried use :includes , :references avoid n + 1 query.

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

but seems n + 1 query still occurs. what's wrong this?

sql (0.2ms)  select `albums`.`id` t0_r0, `albums`.`product_num` t0_r1, `albums`.`created_at` t0_r2, `albums`.`updated_at` t0_r3, `posts`.`id` t1_r0, `posts`.`title` t1_r1, `posts`.`date` t1_r2, `posts`.`post_module_id` t1_r3, `posts`.`post_module_type` t1_r4, `posts`.`created_at` t1_r5, `posts`.`updated_at` t1_r6 `albums` left outer join `posts` on `posts`.`post_module_id` = `albums`.`id` , `posts`.`post_module_type` = 'album' post load (0.3ms)  select `posts`.* `posts` `posts`.`post_module_id` = 18 , `posts`.`post_module_type` = 'album' order `posts`.`id` asc limit 1 post load (0.2ms)  select `posts`.* `posts` `posts`.`post_module_id` = 20 , `posts`.`post_module_type` = 'album' order `posts`.`id` asc limit 1 post load (0.2ms)  select `posts`.* `posts` `posts`.`post_module_id` = 21 , `posts`.`post_module_type` = 'album' order `posts`.`id` asc limit 1 post load (0.2ms)  select `posts`.* `posts` `posts`.`post_module_id` = 22 , `posts`.`post_module_type` = 'album' order `posts`.`id` asc limit 1 post load (0.1ms)  select `posts`.* `posts` `posts`.`post_module_id` = 23 , `posts`.`post_module_type` = 'album' order `posts`.`id` asc limit 1 

you trying eager loading in polymorphic association.

please refer following site more details

polymorphic association , eager loading issues

please try

album.all.includes(:post => :post_module) 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -