I was wondering if it was possible to have rails use an inner/outer
join to eager fetch a belongs_to association, rather than having it
generate multiple SQL queries?
In this case, here are my model objects with the assoications:
class Restaurant < ActiveRecord::Base
belongs_to :state
end
class State < ActiveRecord::Base
has_many :restaurants
end
In my controller action, I am currently doing…
@restaurant = Restaurant.find(params[:id], :include => [:state])
… which is causing multiple SQL queries to be generated, one to
select the restaurant info, and the other to select the state info. Is
there a way to easily override this default behavior and have rails
generate a single query with an INNER or OUTER join while still
populating the state info for the restaurant?
I did a bit of research on the changes to ActiveRecord between 2.0 and
2.1, and I understand why the default behavior is to generate multiple
SQL queries, since in the case where you have a relationship such as
has_many that is referenced in the :include, if ActiveRecord were to
use a single SQL query, AR might end up having to parse a number of
records much larger than the number of distinct rows you will be
displaying.
I am also aware that if you invoke a condition on a row not in the
table corresponding to the model object in the call to find(), that
ActiveRecord will fall back on the old method of generating a single
query with joins. However, I would prefer to not add any conditions,
as that seems like kind of a hack. If absolutely necessary, I suppose
I a condition like “states.id = restaurants.state_id” could be added,
but that just seems altogether ugly.
However, in some cases, such as the one I mention above, I think it
might be desirable to be able to ask ActiveRecord to generate a single
query, since the result of the SQL would be at most a single row
anyhow.