Rails 3 fields_for agressive loading?

Posted by Seth on Stack Overflow See other posts from Stack Overflow or by Seth
Published on 2010-12-24T02:45:08Z Indexed on 2010/12/24 2:54 UTC
Read the original article Hit count: 190

Filed under:
|
|
|

Hi all, I'm trying to optimize (limit) queries in a view. I am using the fields_for function. I need to reference various properties of the object, such as username for display purposes. However, this is a rel table, so I need to join with my users table. The result is N sub-queries, 1 for each field in fields_for. It's difficult to explain, but I think you'll understand what I'm asking if I paste my code:

<%= form_for @election do |f| %>
  <%= f.fields_for :voters do |voter| %>
    <%= voter.hidden_field :id %>
    <%= voter.object.user.preferred_name %>              
  <% end %>
<% end %>

I have like 10,000 users, and many times each election will include all 10,000 users. That's 10,000 subqueries every time this view is loaded. I want fields_for to JOIN on users. Is this possible?

I'd like to do something like:

...
<%= f.fields_for :voters, :joins => :users do |voter| %>
  ...
<% end %>
...

But that, of course, doesn't work :(

© Stack Overflow or respective owner

Related posts about sql

Related posts about ruby-on-rails