Search code examples
sqlruby-on-railsjoinfields-for

Rails 3 fields_for agressive loading?


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 :(


Solution

  • you could just ensure that the voters relationship always joins with users in the election model.

    class Election < ActiveRecord::Base
      has_many :voters, :include => :users
    end
    

    Read the Rails documentation on associations and the extra options you can provide when declaring relationships in the model.

    http://railsapi.com/doc/rails-v3.0.1/classes/ActiveRecord/Associations/ClassMethods.html#M001055