Using :joins - How to help Rails populate a list of records


#1

Hi,

Due to some performance issues, I want to use a custom query for a find
method:

def find_in_state(state)
State.find :all,
:limit => 10,
:conditions => ['s.id = ? AND ’ +
's.id = c.state_id AND c.state_id = ? AND
’ +
'c.id = col.county_id AND ’ +
's.id = l.state_id AND l.state_id = ? AND
’ +
'g.id = l.group_id AND ’ +
‘sc.location_id = l.id’,
state, state, state],
:joins => ‘s, counties c, colonies col, locations l,
groups g, schools sc’,
:select => ‘c., col., l., g., sc.*’
end

Basically, it searches for schools in a specific state, and joins with
related tables, like “counties”, “locations”, “colonies”…

However, as I’m aware, it’s not possible to tell from which table does
each column belong to, as there are column names shared between
different tables.

So I’m wondering if it’s possible to give Rails a hand so it builds
the object relationship like so:

@schools = find_in_state(9) -> this should build:

@schools.state
@schools.location
@schools.location.county

etc.

If it isn’t possible, how does one do it manually?

Thanks in advance!

Ivan V.