Question

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

Was it helpful?

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

OTHER TIPS

So, I have no idea how to do this, but I found a way around it. I overrode election.voters in my model to return joined on users...

You can also create a named scope that joins users

class Election < ActiveRecord::Base
  has_many :voters
  scope :with_voters, :include => :voters
  …
end

then you can use something like Election.with_voters.first

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top