Ed Haywood
Ed Haywood

Reputation: 335

active record query conflict between :joins and :includes

Can anyone suggest an easy fix for the query below?

Workout.all(:joins => [:person, :schedule], 
        :conditions => ["schedule.id = ? AND people.gym_id = ?", schedule.id, gym.id ], 
        :order => "time DESC",
        :include => [:person]),

Error message says Mysql::Error: Not unique table/alias: 'people': and then a very long sql query

When I remove :person from the :include options, the code works fine. However, then I get the "n+1 queries" problem: when I display the workouts, it generates a separate query for each person.

I am assuming that the 'people' tables from the join and include options conflict in the generated SQL. Is there a way to alias tables with active record using the find options? Or do I need to use a sql fragment for the :joins option so that I can alias the tables with AS?

I have not upgraded this app to 3.0 yet, so I can't use the "Class.joins().where()" syntax.

Upvotes: 1

Views: 470

Answers (1)

Shiv
Shiv

Reputation: 8412

You can remove :person from the joins and keep it in the include, you can add fields from the people table in the :select option e.g

Workout.all(:joins => [:schedule], 
    :conditions => ["schedule.id = ? AND people.gym_id = ?", schedule.id, gym.id ], 
    :order => "time DESC",
    :select => "workouts.*,people.*"
    :include => [:person])

Upvotes: 2

Related Questions